我有一个图像动画问题需要修复。当用户将鼠标悬停在图像上时,图像的尺寸应增加。当用户从图像中移出时,图像应返回到其原始大小。
问题:当用户快速移出图像时,图像会膨胀并开始扭曲,或者更改为完全不同的尺寸。然后,当鼠标未悬停在图像上时,它会继续播放动画。
这是问题的一部分 JSFiddle
我在 .on()
方法中使用 mouseover
和 mouseout
事件时遇到了同样的问题。此外,在 .on()
方法中将这些事件链接在一起
HTML:
<div id="content">
<img id="foo" src="http://www.nasa.gov/images/content/297522main_image_1244_946-710.jpg" alt="" title="" />
jQuery:
jQuery('#content').on("hover", '#foo', function (e) {
var $img = jQuery(this);
var $imgWidth = $img.width();
var $imgHeight = $img.height();
var $imgTop = $img.position().top;
if (e.type == "mouseenter") {
$img.animate({
top: $imgTop - 20,
width: $imgWidth * 1.2,
height: $imgHeight * 1.2
}, 200);
} else if (e.type == "mouseleave") {
$img.animate({
top: $imgTop + 20,
width: $imgWidth / 1.2,
height: $imgHeight / 1.2
}, 200);
}
});
最佳答案
每次将鼠标悬停在图像上时,即使图像处于动画状态,您也会获得图像的宽度和高度,因此当前值并不是您真正想要的值。
相反,存储原始值并处理这些值:
jQuery('img').load(function() {
var $this = jQuery(this);
$this.data({
'orig-width': $this.width(),
'orig-height': $this.height(),
'orig-top': $this.position().top
});
});
jQuery('#content').on("hover", '#foo', function(e) {
var $this = jQuery(this);
if (e.type == "mouseenter") {
$this.stop().animate({
top: $this.data('orig-top') - 20,
width: $this.data('orig-width') * 1.2,
height: $this.data('orig-height') * 1.2
}, 200);
} else if (e.type == "mouseleave") {
$this.stop().animate({
top: $this.data('orig-top'),
width: $this.data('orig-width'),
height: $this.data('orig-height')
}, 200);
}
});
关于javascript - 使用 jQuery .animate() 时的图像动画问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13144420/