向上滚动时使Div返回其原始位置

时间:2013-12-10 04:29:35

标签: javascript jquery jquery-ui

当你向下和向上滚动时,我有一个带动画的div,问题是当我快速向上和向下滚动而不让div完成动画时,div一点一点地从屏幕上方移出

如果我删除.animate()函数中的.stop()并快速向上和向下滚动,div会暂时保持这种状态。

我想在上下滚动时保持动画,唯一的区别是当快速上下滚动时菜单没有离开屏幕,我看起来像这样的彻底的堆栈溢出问题,但我找不到任何东西工作jsfiddle的代码可以在这里找到:

http://jsfiddle.net/QLLkL/4/

$(window).scroll(function(){
    if($(window).scrollTop() > 480 && !animationStarted){
         $("#menu").stop().animate({ "top": "+=180px" }, 1000);
        animationStarted  = true;
    };
    if($(window).scrollTop() < 480 && animationStarted){
         $("#menu").stop().animate({ "top": "-=180px" }, 1000);          
        animationStarted  = false;
    };        
});

3 个答案:

答案 0 :(得分:3)

你为什么使用“+ =”和“ - =”?事实是,当你在没有完成动画的情况下向上滚动时,将获取当前值并从中减去“567px”。我建议你分别做到“567px”和“0px”。 如果您确定不以Internet Explorer 9为目标,您甚至可以尝试CSS3过渡。

请参阅此处的示例:http://jsfiddle.net/myTerminal/QLLkL/6/

$(window).scroll(function(){
        if($(window).scrollTop() > 480 && !animationStarted){
             $("#menu").addClass("bottom");
            animationStarted  = true;
        };
        if($(window).scrollTop() < 480 && animationStarted){
             $("#menu").removeClass("bottom");
            animationStarted  = false;
        };        
});

编辑:更新的示例,适用于Firefox:http://jsfiddle.net/myTerminal/QLLkL/13/错过了之前设置“top:0px”。

答案 1 :(得分:3)

http://jsfiddle.net/prollygeek/QLLkL/14/

$(document).ready(function(){
    var animationStarted = false;
    var x=$("#menu").css("top")   
    $(window).scroll(function(){    
        if($(window).scrollTop()>x)
        {
            $("#menu").stop().animate({ "top": x+"px" }, 20);
        }
        else
        {
            $("#menu").stop().animate({ "top": $(window).scrollTop()+"px" }, 20);
        }
        // animationStarted  = true;              
    });
});

这应该解决所有问题。

答案 2 :(得分:1)

$(document).ready(function(){
    var animationStarted = false;

      $(window).scroll(function(){
        if($(window).scrollTop() > 1 && !animationStarted){
            $("#menu").stop().animate({ "top": $(window).scrollTop()+"px" }, 20);
           // animationStarted  = true;
        };
        if($(window).scrollTop() < 1 && animationStarted){
             ("#menu").stop().animate({ "top":$(window).scrollTop()-50+"px" }, 20);
           // animationStarted  = false;
        };        
    });
});