jQuery滚动事件每次滚动触发一次 [英] jQuery scroll event fire once per scroll

查看:121
本文介绍了jQuery滚动事件每次滚动触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些jQuery代码来检查是否已滚动到窗口底部.

I have some jQuery code to check if I've scrolled to the bottom of the window.

$(window).scroll(function(){
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        appendToGrid();
    }
})

我的appendToGrid()函数将用户滚动到页面顶部并添加内容.问题是,我需要每个滚动一次调用此函数.就像我现在拥有的那样,每个滚动被多次调用.

My appendToGrid() function scrolls the user to the top of the page and adds content. Problem is, I need this function called once per scroll. As I have it now, it is called multiple times per scroll.

如果我将其更改为

$(window).one('scroll',function() {
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        appendToGrid();
    }
});

总共只会触发一次,但是我需要每次滚动触发一次,以便用户可以滚动到底部并保持发送回到页面顶部的状态.

it will only fire once total, but I need it to fire once per scroll so the user can scroll to the bottom and keep getting sent back to the top of the page.

我也尝试了以下方法,但仍会多次触发.

I've also tried the below but it still fires multiple times.

var fired = false;
$(window).scroll(function(){
    if($(window).scrollTop() + $(window).height() == $(document).height() && !fired) {
        fired = true;
        appendToGrid();
        fired = false;
    }
})

推荐答案

调用appendToGrid后,您可以添加一个冷却计时器.这与您的fired标志类似,但仅在2000ms等待后才重置.您可以将时间调整为最合适的时间.

You could add a cooldown timer once appendToGrid is called. This is similar to your fired flag but it only resets after a 2000ms wait. You can adjust that time to whatever feels best.

var recentScroll = false;
$(window).on('scroll',function() {
    if(!recentScroll && $(window).scrollTop() + $(window).height() == $(document).height()) {
        appendToGrid();
        recentScroll = true;
        window.setTimeout(() => { recentScroll = false; }, 2000)
    }
});

这篇关于jQuery滚动事件每次滚动触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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