jQuery在视口检查器中一次查找多个元素 [英] jquery in viewport checker for multiple elements at once

查看:77
本文介绍了jQuery在视口检查器中一次查找多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery函数,用于检查元素是否在视口中.如果是,它将添加"animate"类以启动动画并使该元素可见.

I have a jQuery function that checks if an element is in the viewport or not. If it is it adds the class 'animate' to start an animation and make the element visible.

上面的方法有效,但是现在(具有多个元素)jQuery仅针对类为blogcard的第一个元素.然后对所有元素执行addClass("animate").我希望它在视口中查找每个元素.也许使用jQuery.each()函数.但是我还没有设法解决这个问题.

The above works, but right now ( with multiple elements ) jQuery only targets the first element with the class blogcard. And then executes the addClass("animate") for all elements. I want it to look for each element if it is in the viewport. perhaps with the jQuery.each() function. But I haven't managed to get that working yet.

这是我的代码:

JS:

$.fn.isInViewport = function () {
    let elementTop = $(this).offset().top;
    let elementBottom = elementTop + $(this).outerHeight();
    let viewportTop = $(window).scrollTop();
    let viewportBottom = viewportTop + $(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on("load resize scroll", function () {
    if ($('.blogcard ').isInViewport()) {
        $('.blogcard').addClass("animate");
        console.log('success.')
    }
});

CSS:

.fade-in {
    opacity            : 0;
    -webkit-transition : opacity 2s ease-in;
    -moz-transition    : opacity 2s ease-in;
    -ms-transition     : opacity 2s ease-in;
    -o-transition      : opacity 2s ease-in;
    transition         : opacity 2s ease-in;
}

.fade-in.animate {
    opacity : 1;
}

HTML:

{#Item 1#}
<div class="blogcard fade-in">
    {#Blog content#}
</div>
{#Item 2#}
<div class="blogcard fade-in">
    {#Blog content#}
</div>
{#Item 3#}
<div class="blogcard fade-in">
    {#Blog content#}
</div>

推荐答案

是.您可以使用$ .each()做到这一点:

Yes. You can do it with $.each():

$(window).on("load resize scroll", function () {
    $('.blogcard').each(function() {
        if( $(this).isInViewport() ) {
            $(this).addClass('animate');
        }
    });
});

这篇关于jQuery在视口检查器中一次查找多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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