[英]Image animation issue when using jQuery .animate()
我有一个图像动画问题需要解决。 当用户将鼠标悬停在图像上时,图像的大小应增加。 当用户从图像中移出时,图像应返回其原始大小。
问题:当用户非常快地移入和移出图像时,图像将扩展并开始变形,或者变为完全不同的大小。 然后,当鼠标没有悬停在图像上方时,它将继续进行动画处理。
这是JSFiddle的问题
我在.on()
方法中使用mouseover
和mouseout
事件遇到了相同的问题。 同样,在.on()
方法.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);
}
});
演示: http : //jsfiddle.net/TbDrB/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.