鼠标悬停时的Jquery动画并在mouseout上停止

时间:2012-04-24 05:14:03

标签: jquery animation mouseout mouseenter

我有六个带有此代码的按钮:

$('img#b1').on('mouseenter', function() {
    var height = $('div#b1').css('height');
    if(height == '50px'){
        $('div#b1').animate({
        'width' : '1100'
    }, 200);
    }
});
$('img#b1').on('mouseout', function() {
    var height = $('div#b1').css('height');
    if(height == '50px'){
        $('div#b1').animate({
        'width' : '990'
    }, 200);
    }
});

它可以正常工作,但是如果你快速移动鼠标几次然后将鼠标移出,鼠标就会重新启动动画。

如果没有鼠标,我不想恢复动画。

我该如何解决?

3 个答案:

答案 0 :(得分:4)

这是完美的例子。

$('img#b1')
  .hover(function() {
    $(this).stop().animate({ width: 1100 }, 'fast');
  }, function() {
    $(this).stop().animate({ width: 990 }, 'fast');
  });

http://css-tricks.com/full-jquery-animations/

答案 1 :(得分:2)

您的代码应如下所示:

$('img#b1').on({
    mouseenter: function() {
        var height = $('div#b1').css('height');
        if(height === '50px'){
            $('div#b1').stop().animate({
                width: 1100
            }, 200);
        }
    },
    mouseout: function() {
        var height = $('div#b1').css('height');
        if(height === '50px'){
            $('div#b1').stop().animate({
                width: 990
            }, 200);
        }
    }
});

它使您的代码更清晰。

答案 2 :(得分:1)

你需要像这样停止动画:

$('img#b1').on('mouseenter', function() {
    var height = $('div#b1').css('height');
    if(height == '50px'){
        $('div#b1').stop().animate({
        'width' : '1100'
    }, 200);
    }
});
$('img#b1').on('mouseout', function() {
    var height = $('div#b1').css('height');
    if(height == '50px'){
        $('div#b1').stop().animate({
        'width' : '990'
    }, 200);
    }
});
相关问题