如果元素在视口中 - 停止滚动动画 [英] If element is in viewport- stop scroll animation

查看:35
本文介绍了如果元素在视口中 - 停止滚动动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

它工作得很好,但是,当一个元素已经在视口中时(比如浏览器很小并且页面已加载),那么 jQuery 不会将 CLASS 添加到过渡,直到滚动后.

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?'

推荐答案

尝试

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>

这篇关于如果元素在视口中 - 停止滚动动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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