最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to tell if a DOM element is displayed? - Stack Overflow

programmeradmin3浏览0评论

This is not to be confused with "How to tell if a DOM element is visible?"

I want to determine if a given DOM element is visible on the page. E.g. if the element is a child of a parent which has display:none; set, then it won't be visible.

(This has nothing to do with whether the element is in the viewport or not)

I could iterate through each parent of the element, checking the display style, but I'd like to know if there is a more direct way?

This is not to be confused with "How to tell if a DOM element is visible?"

I want to determine if a given DOM element is visible on the page. E.g. if the element is a child of a parent which has display:none; set, then it won't be visible.

(This has nothing to do with whether the element is in the viewport or not)

I could iterate through each parent of the element, checking the display style, but I'd like to know if there is a more direct way?

Share Improve this question edited May 23, 2017 at 12:14 CommunityBot 11 silver badge asked Dec 2, 2008 at 23:47 EoghanMEoghanM 26.9k24 gold badges94 silver badges126 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 14

From a quick test in Firefox, it looks like the size and position properties (clientWidth, offsetTop etc.) all return 0 when an element is hidden by a parent being display:none.

Using Prototype:

if($('someDiv').visible) {...}

As I'm using MochiKit, what I came up with based on Ant P's answer was:

getElementPosition('mydiv').y != 0

I can also check whether it's in the viewport (vertically) by:

y = getElementPosition('mydiv').y
(y < getViewportPosition().y + getViewportDimensions().h &&
    getViewportPosition().y < y)

Incidentally this also works in IE6.

Relying on the position being 0 is brittle. You're better off writing a helper function to iterate through the parents to check their display style directly.

Here's the iterative solution -

var elementShown = function(e){
    if (e == document) 
      return true;

    if ($(e).css('display') == 'none') //or whatever your css function is
      return false;

    return elementShown(e.parentNode);
}

.getClientRects() will return an empty array if the element is not displayed by inheritance (display="none" from parent/ancestor element)

发布评论

评论列表(0)

  1. 暂无评论