如何获取视口中可见的第一个DOM元素? [英] How to get the first DOM element that is visible in a viewport?

查看:228
本文介绍了如何获取视口中可见的第一个DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取视口中可见的第一个DOM元素?

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

PS:页面中的第一个DOM元素不会是第一个可见元素当我滚动到页面的中间或底部时元素

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

推荐答案

考虑到滚动,你需要查询整个文档,获取元素偏移位置,并再次匹配窗口的 scrollTop 值。然后查询:eq(0)(jQuery)。

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.

编辑:我认为这个样本会起作用,还没有尝试过,因为我无法在工作电脑上访问任何小提琴。

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;
        }
    }
});

这篇关于如何获取视口中可见的第一个DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆