javascript - 使用 jQuery .animate() 时的图像动画问题

标签 javascript jquery image animation jquery-animate

我有一个图像动画问题需要修复。当用户将鼠标悬停在图像上时,图像的尺寸应增加。当用户从图像中移出时,图像应返回到其原始大小。

问题:当用户快速移出图像时,图像会膨胀并开始扭曲,或者更改为完全不同的尺寸。然后,当鼠标未悬停在图像上时,它会继续播放动画。

这是问题的一部分 JSFiddle

我在 .on() 方法中使用 mouseovermouseout 事件时遇到了同样的问题。此外,在 .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/

关于javascript - 使用 jQuery .animate() 时的图像动画问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13144420/

相关文章:

javascript - 使用 Promise 处理 Promise 的数组结果

javascript - 无效的正则表达式错误

python - 计算方差图像python

javascript - 使用 javascript 从图像数组更改 img 标签 src。骰子游戏

javascript - 显示来自缓存浏览器的图像

javascript - 为什么我的 JavaScript 不工作?我的正则表达式似乎有问题,但我无法弄清楚

javascript - 对 Canvas 中的图像进行像素精确的命中检测?

javascript - JS链接不起作用

jquery - 倒计时进度条为0时如何添加代码?

jquery - 如何使用 jQuery 使 div 的所有 4 个角都有可调整大小的 handle ?