条件匹配后仅运行jQuery事件一次 [英] Run jQuery event only once after a condition matches

查看:100
本文介绍了条件匹配后仅运行jQuery事件一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作在线产品网站,我触发了一个滚动事件,在启动时只会显示12个元素,但当第8个元素滚动到顶部滚动事件时,应该只运行一次,但每次向下滚动时都会运行, 请帮忙。
这里是我的代码:

I am making online product site, I am trigging a scroll event, at starting only 12 elements will be shown but when 8th element is scrolled to top scroll event should run only once, but it is running every time when I scroll down, please help. Here is my Code:

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top;  
    $(window).on("scroll",function(){
        var scroll_top = $(window).scrollTop(); // current vertical position from the top
        // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
        if (scroll_top > sticky_navigation_offset_top) 
        { 
            console.log("Hi");
        }       
    });


推荐答案

我认为您需要的是 .one 方法

$(window).one("scroll",function(){
    var scroll_top = $(window).scrollTop(); // current vertical position from the top
    // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
    if (scroll_top > sticky_navigation_offset_top) 
    { 
        console.log("Hi");
    }       
});

您可以在这里了解更多信息: http://api.jquery.com/one/

You can learn more here: http://api.jquery.com/one/

这篇关于条件匹配后仅运行jQuery事件一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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