2016-02-27 76 views
1

我們正在嘗試當滾動和顯示回來時,用戶會停止滾動來實現簡單的隱藏菜單,但.on('scroll')的作品,但.off('scroll')關閉的jQuery(「滾動」)不工作

$(document).on('scroll',hideMenu); 
$(document).off('scroll',showMenu) 
function hideMenu(){ 
    $('#home_menu').fadeOut(); 
} 
function showMenu(){ 
    $('#home_menu').fadeIn(); 
} 

發生了什麼? 當我們開始滾動菜單消失,但是當我們停止滾動時,不褪色它

+1

你嘗試讀取jQuery的API文檔? – MysterX

+3

['jQuery.off'](http://api.jquery.com/off#entry-longdesc)用於刪除一個處理程序,以便它不再爲該事件調用。 –

+0

'on'addEventListener,'off'刪除它 – sglazkov

回答

2

你可以利用setTimeout代替,將被取消(清除)每次有一個滾動,而當滾動停止時,使其執行showMenu

var menuTimer; 
 
$(window).on("scroll", hideMenu); 
 

 
function hideMenu() 
 
{ 
 
    clearTimeout(menuTimer); 
 
    $('#home_menu').fadeOut(); 
 
    menuTimer = setTimeout(showMenu, 900); 
 
} 
 

 
function showMenu() 
 
{ 
 
    $('#home_menu').fadeIn(); 
 
}
body{padding-top:3em;font-family:Arial,Helverica,sans-serif} 
 
#home_menu{position:fixed;top:0;left:0;width:100%;padding:1em;background:#1b83db;color:#fff} 
 
p{margin-bottom:3em}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="home_menu">Menu</div> 
 

 
<p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p><p>Some text</p>

+0

這是一些確切的答案,我會喜歡的本地版本(我想它不存在),但如果它的工作,我沒有問題:) – runningmark

+0

@runningmark對不起,延遲,但你是什麼意思的「本地版本「?沒有jQuery?或者相當於你想要做什麼?.off('scroll')'做什麼? – blex

+0

我道歉不清楚,本機我的意思是不使用間隔:) – runningmark

0

這裏有一個誤區:

.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(); 
    } 
}