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

当你向下和向上滚动时,我有一个带动画的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; }; }); 

你为什么用“+ =”和“ – =”? 事实是,当您在没有动画完成的情况下向上滚动时,将获取当前值并从中减去“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”。

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; }); }); 

这应该解决所有问题。

 $(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; }; }); });