有沒有辦法阻止$(window).scroll()
在頁面加載時觸發?
在Firefox 4中測試以下代碼,即使在拔下鼠標時也會觸發。
jQuery(document).ready(function($){
$(window).scroll(function(){
console.log("Scroll Fired");
});
});
有沒有辦法阻止$(window).scroll()
在頁面加載時觸發?
在Firefox 4中測試以下代碼,即使在拔下鼠標時也會觸發。
jQuery(document).ready(function($){
$(window).scroll(function(){
console.log("Scroll Fired");
});
});
scroll
事件與鼠標無關,只要設置了新的文檔滾動位置,就會調用它。並且可以證明,當文檔加載時(可能最後加載一個錨點),該位置被設置,如果用戶在他的鍵盤上按下光標鍵。我不知道爲什麼你需要忽略最初的scroll
事件,但我想你只是想要這樣做,如果pageYOffset
爲零。這很簡單:
var oldPageYOffset = 0;
$(window).scroll(function(){
if (window.pageYOffset != oldPageYOffset)
{
oldPageYOffset = window.pageYOffset;
console.log("Window scrolling changed");
}
});
注:MSIE沒有window.pageYOffset
屬性,因此上面的需要進行調整。也許jQuery提供了一個跨瀏覽器的選擇。
這幾乎就在那裏,我簡直就是需要防止第一次運行! –
@Mild Fuzz:如果你解釋你想要達到的目標而不是你想達到目標的方式,你會得到更好的答案。認爲忽略第一個滾動事件對你來說是最好的解決方案,但這可能不是這種情況(並且不可能告訴你是否不提供更多信息)。無論哪種方式,你也可以用'window.pageYOffset'來初始化'oldPageYOffset' '如果你絕對想忽略最初的'scroll'事件 –
當然,直到加載後才加載。使其成爲500毫秒的睡眠呼叫。
它不是,上面的代碼加載在'jQuery(document).ready(function($){ ' –
添加到示例代碼 –
這是我去的解決方案。感激地收到任何改進。
var scroll = 0;
$(window).scroll(function(){
if (scroll>0){
console.log("Scroll Fired");
}
scroll++;
});
好的解決方案!:) – Steve
僅當刷新滾動的頁面或直接導航到錨點時,滾動事件纔會在每次加載時觸發。
許多答案建議忽略它第一次被調用,如果頁面最初沒有滾動,它會忽略有效的滾動。
//Scroll the page and then reload just the iframe (right click, reload frame)
//Timeout of 1 was not reliable, 10 seemed to be where I tested it, but again, this is not very elegant.
//This will not fire initially
setTimeout(function(){
$(window).scroll(function(){
console.log('delayed scroll handler');
});
}, 10);
//This will fire initially when reloading the page and re-establishing the scroll position
$(window).scroll(function(){
console.log('regular scroll handler');
});
div {
height: 2000px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
你在哪裏需要防止滾動任何的例子嗎? – genesis
我只需要防止在沒有滾動發生時觸發滾動事件。 –
當心掛鉤窗口滾動事件http://ejohn.org/blog/learning-from-twitter/ – redsquare