jquery滚动事件的计时问题(有时候工作正常并且有时会延迟)

时间:2014-01-25 13:27:43

标签: javascript jquery html css

我试图在jquery scroll()事件中隐藏一些div。但是一些时间问题正在出现问题,因此有时(或大多数时间)动画变得怪异。向下滚动它必须隐藏,当向上滚动时它必须可见但是它们的时间设置不正确(延迟大部分时间),当我向下滚动突然时它会变得可见再次。我希望这个效果类似于这个网站:http://www.flipkart.com/,即平滑协调的计时效果,但不知道该怎么办!我怎样才能像在那个网站(前面提到的那样)那样协调一致呢? 在http://jsfiddle.net/ankur3291/HnS5m/检查我的工作代码。

$(document).ready(function(){
lastScroll=0;
$(document).scroll(function(){
    st=$(document).scrollTop();
    $(".top").html("<h1>"+st+"</h1>");
    if(st > lastScroll){
        //downward scrolling...
        //$(".strip").animate({top:'-30px'},20);
        $(".top").animate({top:'0px'},100);
        $(".menu").animate({top:'20px'},100);
    }
    else{
        //upward scrolling...
        //$(".strip").animate({top:'0px'},20);
        $(".top").animate({top:'30px'},100);
        $(".menu").animate({top:'130px'},100);
    }
    lastScroll=st;
});
});

1 个答案:

答案 0 :(得分:0)

现在我明白了!... .animate()函数每次发生事件时都会创建一堆调用,需要在每个stop()函数之前使用.animate()函数停止。 stop()函数有两个参数(默认都是false),第一个参数是[clearQueue],即如果我们需要清除队列(生成的调用)然后输入true,否则返回false,第二个参数是[jumpToEnd],即完成时如果我们需要完成动画设置为true,否则为false。有关详情,请访问http://api.jquery.com/stop/

检查此修复fiddle

参见代码:

$(document).ready(function(){
    lastScroll=0;
    $(document).scroll(function(){
        st=$(document).scrollTop();
        $(".top").html("<h1>"+st+"</h1>");
        if(st > lastScroll & st>100){
            //downward scrolling...
            //$(".strip").animate({top:'-30px'},20);
            $(".top")
                .stop(true,false)    //This needs to be implemented for stack clearing...
                .delay(100)          //for time setting..
                .animate({top:'0px'},100);
            $(".menu")
                .stop(true,false)    //here too...
                .delay(100)
                .animate({top:'20px'},100);
        }
        else{
            //upward scrolling...
            //$(".strip").animate({top:'0px'},20);
            $(".top")
                .stop(true,false)    //here too...
                .delay(100)
                .animate({top:'30px'},100);
            $(".menu")
                .stop(true,false)    //here too...
                .delay(100)
                .animate({top:'130px'},100);
        }
        lastScroll=st;
    });
});