jQuery-检测元素是否在视口中 [英] jQuery - Detecting if element is in viewport

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

问题描述

我正在编写一个脚本,该脚本在屏幕上出现不同元素时会给它们一些动画。

I am writing a script that gives different elements some animations when they appear in the screen.

第一步是检测它们何时出现在屏幕上。

Step one would be to detect when they come in the screen. But that doesn't seem to work.

我尝试过的事情:

- .visible()选择器,我很快发现它在jQuery中还有其他功能。

-The .visible() selector, I quickly found out this does something else in jQuery.

不同的插件,但我发现它们确实可以

-Different plugins, but I found that they do way more then I need, therefore I decided to write/ find something myself.

-我当前的脚本(我在论坛的某个地方找到了它,并决定将其编辑为我自己的脚本)。

-My current script (I found it somewhere in a forum and decided to edit it to my needs) But It works a little strange.

$.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).scroll(function () {
    if ($('.blogcard ').isInViewport()) {
        $(this).addClass("test");
        console.log('success.')
    } else {
        console.log('No success.')
    }
});

不幸的是,这似乎并没有为我的< div添加类class ='blogcard'>

Unfortunately this doesn't seem to add a class to my <div class='blogcard'>.

推荐答案

您对 this的使用不针对窗口。 Blogcard元素:

Your use of "this" targets window not .blogcard element:

$(window).scroll(function () {
    if ($('.blogcard ').isInViewport()) {
        //  Use .blogcard instead of this
        $('.blogcard').addClass('test');
        console.log('success.')
    } else {
        //  Remove class
        $('.blogcard').removeClass('test');
        console.log('No success.')
    }
});

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

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