How to get the first DOM element that is visible in a viewport?

老子叫甜甜 提交于 2019-12-11 02:26:25

问题


How can I get the first DOM element that is visible in a viewport?

PS: the first DOM element in a page will not be the first "visible" element when I scroll to the middle or bottom of the page


回答1:


In mind with the scroll, you'll need to query the whole document, get the elements offset positions, and match that agains the scrollTop value of the window. Then query the :eq(0) (jQuery) of those.

EDIT: I think this sample will work, haven't tried it out yet tho, since I'm unable to access any fiddle here at work computers.

$(function () {
    var scroll = $(window).scrollTop();
    var elements = $("*"); // VERY VERY bad performance tho, watch out!
    var el;
    for (var i=0; i<elements.length; i++) {
        el = $(elements[i]);
        if (el.offset().top >= scroll && el.is(':visible')){
            // "el" is the first visible element here!
            // Do something fancy with it

            // Quit the loop
            break;
        }
    }
});


来源:https://stackoverflow.com/questions/17919245/how-to-get-the-first-dom-element-that-is-visible-in-a-viewport

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