【问题标题】:Image animation issue when using jQuery .animate()使用 jQuery .animate() 时的图像动画问题
【发布时间】:2012-10-20 02:42:30
【问题描述】:

我有一个图像动画问题需要解决。当用户将鼠标悬停在图像上时,图像的大小应该会增加。当用户离开图像时,图像应该恢复到原来的大小。

问题:当用户快速移出图像时,图像会扩大并开始自行扭曲,或者变成完全不同的大小。然后在鼠标没有悬停在图像上时继续动画。

这是一个问题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);
    }
});

【问题讨论】:

    标签: javascript jquery image animation jquery-animate


    【解决方案1】:

    每次将鼠标悬停在图像上时,您都会获取图像的宽度和高度,即使图像正在制作动画,所以当前值并不是您真正想要的值。

    相反,存储原始值并处理这些值:

    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/

    【讨论】:

    • 谢谢。你能解释一下存储这些数据吗?如果我有多个图像,使用相同的方法怎么办?
    • 对于其他任何人,是的,这确实适用于多个图像。见小提琴。 jsfiddle.net/TbDrB/13
    猜你喜欢
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多