2017-07-20 137 views
0

出於某種原因,我需要end.So我寫這樣的事情耽誤點擊的preventDefault了一段時間,當滾動頁面:removeEventListener似乎不工作?

// const disableClickDuringScrollHandler=(e)=> { 
//  e.preventDefault(); 
// }; 
this.scrollHandler = e => { 
    console.log('scrolling'); 
    const disableClickDuringScrollHandler = (e) => { 
    e.preventDefault(); 
    }; 
    document.addEventListener('click', disableClickDuringScrollHandler); 
    window.clearTimeout(this.scrollTimer); 
    this.scrollTimer = window.setTimeout(() => { 
    console.log('scroll end'); 
    document.removeEventListener('click', disableClickDuringScrollHandler); 
    }, 300); 
} 
window.addEventListener('scroll', this.scrollHandler); 

我還一直寫codepen:https://codepen.io/zhangolve/pen/gRNMoX

我的問題當我在scrollHandler之外放置disableClickDuringScrollHandler時,removeEventListener可以很好地工作,但是當我在scrollHandler裏面放置disableClickDuringScrollHandler時,removeEventListener似乎不起作用。

我已經嘗試了很多次才發現原因,但失敗了。所以我到這裏來問你的幫助。

+0

它看起來像你正試圖阻止滾動過程中點擊。你想用這個解決什麼問題? –

+0

在移動網站上,當滾動頁面時,如果有人觸摸屏幕讓滾動結束,有時會觸發點擊並重定向到另一個href位置。爲避免此問題,我編寫了一些類似的代碼。@ Rajesh P https ://stackoverflow.com/questions/44095681/how-to-avoid-direct-to-another-anchor-when-scroll-mobile-device-screen-and-touch –

回答

1

問題是,每次用戶滾動時,都會創建一個新的disableClicksDuringScroll閉包並將其添加爲點擊偵聽器。當這個定時器運行時,它會刪除最新的點擊監聽器,但不是以前的監聽器(因爲它們是不同的閉包,所以它們不等於你這次刪除的函數)。

您應該在scroll處理程序之外定義disableClicksDuringScroll函數一次,因爲它在此處不引用任何局部變量。然後當你打電話給removeEventListener它會發現這個處理程序。

您還可以使用變量,因此您只在滾動開始時添加一次點擊偵聽器,而不是每次重置計時器。

this.disableClickDuringScrollHandler = (e) => { 
 
    e.preventDefault(); 
 
}; 
 

 
this.inScroll = false; 
 

 
this.scrollHandler = e => { 
 
    console.log('scrolling'); 
 
    if (!this.inScroll) { 
 
    document.addEventListener('click', this.disableClickDuringScrollHandler); 
 
    this.inScroll = true; 
 
    } 
 
    window.clearTimeout(this.scrollTimer); 
 
    this.scrollTimer = window.setTimeout(() => { 
 
    this.inScroll = false; 
 
    console.log('scroll end'); 
 
    document.removeEventListener('click', disableClickDuringScrollHandler); 
 
    }, 300); 
 
} 
 
window.addEventListener('scroll', this.scrollHandler);