当滚动条达到150像素时我试图隐藏菜单
HTML格式:

<html>
<body style="height:2000px">
    <div id="header">
    </div>
</body>
</html>

CSS:
#header{height:200px; background:#000; position:fixed; top:0; width:100%;}

JS公司:
$(function(){
    $(window).bind('scroll', function(){
        if($(this).scrollTop() >= 150) {
            $('#header').attr('data-open','open');
        }
        if($(this).scrollTop() >= 150 && $('#header').attr('data-open') == 'open'){
            $("#header").animate({top:'-180px'},500, 'linear').attr('data-open','open');
        }else{
            $("#header").animate({top:'0'},500, 'linear').removeAttr('data-open');
        }
    });
});

演示:http://jsfiddle.net/egZ6H/1/
它看起来很有用,但当我回到上面时,有时显示菜单的动画开始得有点晚,反之亦然。
这是什么原因?

最佳答案

您需要在每次动画调用之前调用.stop(),以确保它不会在开始此动画之前等待完成最后一个动画。
updated jsFiddle
代码是:

$(function(){
    $(window).bind('scroll', function(){
        if($(this).scrollTop() >= 150) {
            $('#header').data('open','open');
        }
        if($(this).scrollTop() >= 150 && $('#header').data('open') == 'open'){
            $("#header").stop().animate({top:'-180px'},500, 'linear').data('open','open');
        }else{
            $("#header").stop().animate({top:'0'},500, 'linear').data('open', null);
        }
    });
});​

10-04 22:42
查看更多