开发者

Testing element visibility in jQuery

What is the best way to determine if an element is truly visible on the page? As in pixels are being changed both because the element is not hidden via CSS and is in the visible part of a scrollable area (the window or some overflowing block element)?

I imagine I'll need to first check .is(':hidden') against the element and its parents. I would then need to iterate through all parents and the window, checking for overflow scroll/auto/hidden, then compare that parent element's scroll position and size against the original element's position and size. And I would also need to check for a开发者_StackOverflow中文版bsolute positioning and look at z-indexes, as well.

Is there an easier way?


There's a plugin for that. jQuery inview event plugin


I've implemented $.inside plugin, where you can specify an ancestor, in your case:

$('html').css('height', '100%');   // make `html` the height of the viewport
$('#your-element').inside('html'); // compare `#your-element` to `html`

will return for example:

{
  left: 0.2,  // your element is "x-inside" (because >0 and <1)
  top: -2.3   // but is not "y-inside" (because <0)
}

See the README for more info.

In your case you can add additional check on is(':hidden') and z-index

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜