gpt4 book ai didi

jquery - 为什么基于 window.scrolltop 调整 css 可以一致工作,而 animate 却不能?

转载 作者:行者123 更新时间:2023-12-01 07:21:45 25 4
gpt4 key购买 nike

以下代码获取scrollTop值并按预期​​调整css:

      $(window).scroll(function() {
if($window.scrollTop()>918){
$menu.css({top:'0px'});
}
else{
$menu.css({top:'80px'});
}
}

但是下面的(效果更好)却没有。当滚动事件完成时,它似乎间歇性地触发

       $(window).scroll(function() {
if($window.scrollTop()>918){
$menu.animate({top:'0px'},100);
}
else{
$menu.animate({top:'80px'},100);
}
}

有人知道为什么吗?如此简单却让我精神不振。当然我错过了一些东西,非常感谢任何帮助

最佳答案

因为当用户移动滚动条时,滚动事件会触发很多次,每次触发时都会启动一个新的动画,因此最终会得到一堆同时运行的动画,这些动画都试图以不同方式移动菜单。

如果您像这样停止之前的动画,它可能会起作用:

$(window).scroll(function() {
if($window.scrollTop()>918){
$menu.stop(true).animate({top:'0px'},100);
} else {
$menu.stop(true).animate({top:'80px'},100);
}
}

但是,如果您在执行动画之前等待滚动操作完成,效果可能会更好。请参阅this post用于等待滚动完成的 jQuery 插件方法。

<小时/>

编辑:我有一个更好的主意。在第一次滚动移动时启动动画并允许其继续播放,除非值发生变化:

$(window).scroll(function() {
var menuTarget = $window.scrollTop()>918 ? "0px": "80px";
// only do an animation if one isn't already going or
// the current animation target is not what we want
if (!$menu.is(":animated") || $menu.data("animTarget") !== menuTarget) {
// set the new target, stop the current animation and start new animation
$menu.data("animTarget", menuTarget)
.stop(true).animate({top: menuTarget},100);
}
}

关于jquery - 为什么基于 window.scrolltop 调整 css 可以一致工作,而 animate 却不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12955810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com