繁体   English   中英

jQuery滚动事件每个滚动一次

[英]jQuery scroll event fire once per scroll

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

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

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

如果我改成它

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

它只会触发一次,但我需要它每次滚动一次,所以用户可以滚动到底部并继续发送回页面顶部。

我也尝试过以下但它仍然会多次发射。

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

一旦调用appendToGrid,您可以添加冷却计时器。 这类似于你的fired标志,但它只在等待2000ms后重置。 您可以将时间调整到最佳状态。

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

另一种选择是限制逻辑,使其仅在用户停止一段时间后才发生。

 $(function(){ //cache common variables so they are created once var $window = $(window); var $document = $(document); var debounce; $window.on('scroll', function(){ //clear the delay if it's not finished yet if (debounce) clearTimeout(debounce); //start a new delay debounce = setTimeout(function(){ //remove reference so another delay can start debounce = null; //perform whatever logic you normally would do if($window.scrollTop() + $window.height() == $document.height()) { appendToGrid(); } }, 300); }); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM