2015-05-02 33 views
0

我在頁面上有一個按鈕。當我單擊按鈕時,頁面向下滾動到指定的目標,然後爲scroll事件添加事件偵聽器window,但滾動事件會立即觸發,而不是下次用戶滾動時觸發。window.addEventListener('scroll',func)在window.location =「#target」後觸發

有人可以告訴我爲什麼會發生這種情況,以及在滾動到指定目標後如何將滾動事件添加到window?我使用的是Firefox 37.0.2

HTML

<button>Click Me!</button> 
<!-- Enough br tags to make the page have a scroll bar --> 
<div id="target">Text</div> 

JS

document.getElementsByTagName('button')[0].addEventListener('click', function(){ 
    // Both of the following will trigger the scroll event: 

    //window.location = '#target'; 
    //document.getElementById('target').scrollIntoView(); 

    window.addEventListener('scroll', function(){ 
     // Removes this function from the window's onscroll event so that it only triggers once 
     this.removeEventListener('scroll', arguments.callee); 
     alert('Triggered!'); 
    }); 
}); 
+0

爲什麼要用#導航。使用scrollintoview或jquery插件導航,它也支持回調(在滾動完成後運行),這將解決您的問題。另外,在我看來,你應該指定你的目標是什麼瀏覽器。 tl; dr:您正在描述正常的瀏覽器行爲。您可以通過正確排序來避免這種情況。 – TigOldBitties

+0

@TigOldBitties我對#navigation和scrollIntoView()都有同樣的問題。在添加onscroll事件計數之前不滾動頁面,以正確​​排序我的事件?另外,我沒有使用jQuery。 –

+0

據我的描述,添加事件監聽器並不等待滾動完成。這就是我的意思是正確的順序。確保它在滾動後添加。 – TigOldBitties

回答

0

通過評論看完後,似乎問題是由瀏覽器不會立即造成滾動。我能夠用簡單的setTimeout解決這個問題,以便將addEventListener延遲1ms。

我修改後的代碼:

document.getElementsByTagName('button')[0].addEventListener('click', function(){ 
    // Both of the following will work now: 

    //window.location = '#target'; 
    //document.getElementById('target').scrollIntoView(); 

    setTimeout(function(){ 
     window.addEventListener('scroll', function(){ 
      // Removes this function from the window's onscroll event so that it only triggers once 
      this.removeEventListener('scroll', arguments.callee); 
      alert('Triggered!'); 
     }); 
    }, 1); 
}); 
相關問題