我正在尝试创建一个 Logo 图像,当窗口滚动时,该图像会以动画方式显示到 50% 大小。我的问题是动画在窗口滚动时运行多次。如何在窗口滚动 > 62px 时使其动画一次,以及在窗口滚动回 62px 以上时再次动画?我尝试添加类并删除它们,但没有运气。我进行了搜索,但找不到重复或类似的问题(如果有的话我就不好了!)。
JSFiddle在这里:http://jsfiddle.net/jtheman/kEtPd/ (在jsfiddle中添加了一些额外的css来模拟我的真实项目)
相关 HTML:
<body>
<header>
<div id="logo">
<img src="/img/logo.png">
</div>
...
CSS:
header { position:relative; }
header #logo { position:absolute; top: 62px; left: 0; width: 365px; height: 53px; }
header #logo img { position:absolute; bottom: 0; left: 0; width: 365px; height: 53px; }
还有我的 jQuery:
$(window).scroll( function() {
var scrollpos = $(window).scrollTop();
if (scrollpos > 62)
{
$('#logo img').stop().animate({ 'width': '182px', 'height': '26px'},1000);
}
else
{
$('#logo img').stop().animate({ 'width': '365px', 'height': '53px'},200);
}
});
最佳答案
您应该检查宽度是否仍为原始大小 (365px
),以便仅在图像尚未开始调整大小时才显示动画:
if (scrollpos > 62)
{
if ($('#logo img').width() == 365){
$('header').css({'position':'fixed','top':'-62px'});
$('#logo img').stop().animate({ 'width': '182px', 'height': '26px'},1000);
}
}
关于jquery - 使 animate() 在 $(window).scroll() 上平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13701708/