jquery off('滚动')无效

时间:2016-02-27 09:38:12

标签: javascript jquery html css

我们正在尝试在滚动时实现简单的隐藏菜单,并在用户停止滚动时显示,但.on('scroll')有效,但.off('scroll')没有

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

发生了什么事? 当我们开始滚动菜单消失时,但当我们停止滚动时,它不会淡化它

2 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这里有一个误解:

.off("scroll") 表示在滚动结束时必须调用回调。

而是分离来自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();
    }
}