How to detect that an Html element is in View?

对着背影说爱祢 提交于 2019-12-13 20:03:08

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/2556168/how-to-detect-that-an-html-element-is-in-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!