簡體   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