2016-02-27 86 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(); 
    } 
}