這裏有一個誤區:
.off("scroll")
確實不是表示當滾動結束時必須調用回調。
取而代之的是detach來自scroll
事件的回調。
你想要的是在滾動開始時調用回調,當它停止時調用另一個回調。
有很多方法可以做到這一點。
這是我的做法(代碼是自我解釋):
$(document).on('scroll',scrollStart);
// A scroll has started
function scrollStart()
{
var lastScrollY;
// record the position
lastScrollY = $(window).scrollTop();
// hide the menu
hideMenu();
// detach the event. We don't want the callback called again for now.
$(document).off('scroll',scrollStart);
// let the function scrollRunning be called after 1 sec
setTimeout(function() { scrollRunning(lastScrollY) }, 1000);
}
// A scroll is going on. Or maybe has ended
function scrollRunning(lastScrollY)
{
var currentScrollY;
// current scroll position
currentScrollY = $(window).scrollTop();
// did the position change ? Scroll is going on
// schedule scrollRunning to check again after 1 sec
if(lastScrollY != currentScrollY) // Scrolling is going on
{
lastScrollY = currentScrollY;
setTimeout(function() { scrollRunning(lastScrollY) }, 1000);
}
else // Scrolling has stopped. Show the menu and reattach the event
{
$(document).on('scroll',scrollStart);
showMenu();
}
}
你嘗試讀取jQuery的API文檔? – MysterX
['jQuery.off'](http://api.jquery.com/off#entry-longdesc)用於刪除一個處理程序,以便它不再爲該事件調用。 –
'on'addEventListener,'off'刪除它 – sglazkov