开发者

How to detect that an Html element is in View?

开发者 https://www.devze.com 2022-12-25 02:08 出处:网络
Using Jquery preferably, how do I detect if an element is within the viewable client area of a browser?

Using Jquery preferably, how do I detect if an element is within the viewable client area of a browser?

I'm dynamically 开发者_如何学编程creating a menu from a dataset, and when the list grows too long, the height of the resulting menu causes part of it to fall below the browser bottom client area. How do I detect this and act accordingly?


I believe it should be possible to cook something up using position() and scrollTop() (add scrollLeft if your page is prone to horizontal scrolling). Here is some untested sample code that should display a message if the target element is (fully or partially) within the viewport:

var pos = $('#element').position(), win = $(window);

if (pos.top < win.height() + win.scrollTop() && pos.bottom > win.scrollTop()) {
    alert('Look at me!');
}

The conditions can be swapped around if you care specifically about full visiblity:

if (pos.bottom < win.height() + win.scrollTop() && pos.top > win.scrollTop()) {

Adding support for horizontal scrolling of the viewport is left as an exercise for the reader :)

0

精彩评论

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