检测div或多个div是否第一次可见

时间:2016-02-14 04:15:07

标签: jquery css scroll

我的页面中有多个div。我怎么能检测到,当页面向下滚动时,div中的任何一个都是第一次可见。

我正在尝试类似的事情:

$('div').offset().top() < $(window).scrollTop()

但肯定不行。处理这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

回答答案的第一部分:当有什么东西进入视野时。 https://stackoverflow.com/a/22480938/825240

function isScrolledIntoView(el) {
    var elemTop = el.getBoundingClientRect().top;
    var elemBottom = el.getBoundingClientRect().bottom;

    var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
    return isVisible;
}

这是第一步。

现在我们需要一种方法来查看之前是否有过div。

var divWeCareAbout = document.getElementById("someDiv");

window.addEventListener("scroll", function(){
    if(isScrolledIntoView(divWeCareAbout)){
        if(!div.dataset.haveSeen){
            //The div had scrolled into view and 
            //this is the first we have seen of it.
            //Do whatever here.
            div.dataset.haveSeen = true;
        }
    }
});
相关问题