如何在滚动上只运行一次jQuery动画?

How can I run a jQuery animation only once on scroll?

本文关键字:一次 jQuery 动画 滚动 运行      更新时间:2023-09-26

我试图使用Javascript来检测用户何时向下滚动超过我网站上的某个高度,然后我的"社交"图标一旦达到滚动断点就会褪色。

我想弄清楚的是我怎么能只运行fadeTo一旦alpha点击1并锁定它?所以当用户再次上下滚动时淡出不会反复发生除非他们重新加载页面那会重置一切。

//SCROLL
$(window).on("scroll", function () {
//SOCIAL ICONS
if ($(this).scrollTop() > 1750) {
    $(".img-social .gith").stop(true).fadeTo(250, 1);
    $(".img-social .inst").stop(true).fadeTo(450, 1);
    $(".img-social .twit").stop(true).fadeTo(650, 1);
    $(".img-social .drib").stop(true).fadeTo(850, 1);
    $(".img-social .link").stop(true).fadeTo(1050, 1);
} else {
    $(".img-social .gith").stop(true).fadeTo(10, 0);
    $(".img-social .inst").stop(true).fadeTo(10, 0);
    $(".img-social .twit").stop(true).fadeTo(10, 0);
    $(".img-social .drib").stop(true).fadeTo(10, 0);
    $(".img-social .link").stop(true).fadeTo(10, 0);
}
});

谢谢

使用布尔值记录是否发生:

// SET BOOLEAN
var scrolled = false;
//SCROLL
$(window).on("scroll", function () {
//SOCIAL ICONS
    if ($(this).scrollTop() > 1750 && !scrolled) {
        $(".img-social .gith").stop(true).fadeTo(250, 1);
        $(".img-social .inst").stop(true).fadeTo(450, 1);
        $(".img-social .twit").stop(true).fadeTo(650, 1);
        $(".img-social .drib").stop(true).fadeTo(850, 1);
        $(".img-social .link").stop(true).fadeTo(1050, 1);
        scrolled = true;
    } else {
        $(".img-social .gith").stop(true).fadeTo(10, 0);
        $(".img-social .inst").stop(true).fadeTo(10, 0);
        $(".img-social .twit").stop(true).fadeTo(10, 0);
        $(".img-social .drib").stop(true).fadeTo(10, 0);
        $(".img-social .link").stop(true).fadeTo(10, 0);
        scrolled = false;
    }
});

只需将以下代码放入您的第一个if条件到off scroll事件中,一旦您运行代码:

$(window).on("scroll.socialIcon", function () {
    if ( $(this).scrollTop() > 1750 ) {
        // ...
        $(window).off("scroll.socialIcon"); // last line
    } else {
        //...
    }
});

因此scroll.socialIcon(命名空间)事件将不再响应