jquery - 如果元素在视口(viewport)中 - 停止滚动动画

标签 jquery css animation sliding

您好,我学习了一个教程:http://css-tricks.com/slide-in-as-you-scroll-down-boxes/

它工作得很好,但是,当一个元素已经在视口(viewport)中时(比如如果浏览器很小并且页面已加载),则 jQuery 不会添加要转换的类,直到滚动后。

有没有办法在加载时检查一个元素是否已经在视口(viewport)中,然后添加一个“已经查看过”的类?

最佳答案

尝试

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>

关于jquery - 如果元素在视口(viewport)中 - 停止滚动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397804/

相关文章:

jquery(移动): use flip switch to change theme of collapsible cotent

javascript - 我们可以使用 jquery 启用浏览器位置吗

html - 悬停仅在从容器 IE 外部进入时有效

html - CSS Sprite 中的 `background-position` 使用负值

javascript - 如何使用 HTML5、Javascript、DOM 和 CSS 创建交互式图像

javascript - 使用 Jquery 搜索 JSON

javascript - django 管理界面 change_form.html 将数据添加到 querydict/post?

javascript - Google charts - 阶梯式图表动画

jquery - CSS3 动画不工作 Firefox

基于速度而不是时间的 CSS 动画?