If element is in viewport- stop scroll animation

◇◆丶佛笑我妖孽 提交于 2019-11-27 04:55:51

问题


Hi I followed a tutorial: http://css-tricks.com/slide-in-as-you-scroll-down-boxes/

It is working just fine, however, when an element is already in viewport (like if the browser is small and the page is loaded), then the jQuery doesn't add the CLASS to transition until AFTER scroll.

Is there a way to check if an element is already in viewport on load and then add a class of 'already-viewed?'


回答1:


Try

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

$(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))
});
body {
    width : 1000px;
    height : 1000px;
}
img {
    width : 50px;
    height : 50px;
    background : navy;
}
.already-viewed {
    outline:0.15em solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


来源:https://stackoverflow.com/questions/28397804/if-element-is-in-viewport-stop-scroll-animation

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