如果元素在视口中 - 停止滚动动画

时间:2015-02-08 18:37:31

标签: jquery css animation sliding

您好我遵循了教程:http://css-tricks.com/slide-in-as-you-scroll-down-boxes/

它正常工作,但是,当一个元素已经在视口中时(如果浏览器很小并且页面被加载),则jQuery不会将CLASS添加到转换,直到AFTER滚动。

有没有办法检查一个元素是否已在加载的视口中,然后添加一个已经查看的类?'

1 个答案:

答案 0 :(得分:1)

尝试

var viewed = Array.prototype.map.call(document.querySelectorAll("body *")
             , function (el, i) {
                return (el.getBoundingClientRect().bottom <= window.innerHeight 
                    && el.getBoundingClientRect().left <= window.innerWidth) 
                    && $(el).addClass("already-viewed") && el
             }).filter(Boolean);

&#13;
&#13;
$(document).ready(function () {
    var body = $("body");
    $.each(new Array(180), function () {
        body.append(
        $("<img>"))
    });
    
    var viewed = Array.prototype.map.call(document.querySelectorAll("body *"), function (el, i) {
        return (el.getBoundingClientRect().bottom <= window.innerHeight 
               && el.getBoundingClientRect().left <= window.innerWidth) 
               && $(el).addClass("already-viewed") && el
    }).filter(Boolean);
    body
    .append("total images: " + $("img").length 
                + ", already viewed: " + $(".already-viewed").length);
    console.log(viewed.length, $(viewed))
});
&#13;
body {
    width : 1000px;
    height : 1000px;
}
img {
    width : 50px;
    height : 50px;
    background : navy;
}
.already-viewed {
    outline:0.15em solid red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;