问题
I got this box that expands on hover after its SVG timer is done:
http://jsfiddle.net/frank_o/WwD5V/9/embedded/result/
But right now it goes bananas if you hover on and off many times quickly. How come placing stop(true,true) before each animate() won't fix it?
JS:
$('.wrapper').bind('mouseenter', function () {
setTimeout(function () {
$('.wrapper').stop(true,true).animate({
width: '100%'
}, 200);
}, 2000);
}).mouseleave(function () {
$('.wrapper').stop(true,true).animate({
width: '120px'
}, 200);
});
HTML:
<div class="wrapper">
<div class="main"></div>
</div>
CSS:
.wrapper {
height: 600px;
width: 200px;
overflow: hidden;
border: 4px solid black;
float: right;
}
回答1:
This function is queue a timeout job for each mouseenter. When the timed function resolves it will stop any animation on the element, but it will not clear other timed functions.
$('.wrapper').bind('mouseenter', function () {
setTimeout(function () {
var $this = $('.wrapper');
$this.stop(true,true).animate({
width: '100%'
}, 200);
$this.find('.main').stop(true,true).animate({
left: '150%'
}, 200);
}, 2000);
});
So to fix, you need to check if the timeout is already set, and clear it first:
$('.wrapper').bind('mouseenter', function () {
var timeoutHandle = $(this).data('timeout') || 0;
if (timeoutHandle > 0)
clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(function () {
var $this = $('.wrapper');
$this.stop(true,true).animate({
width: '100%'
}, 200);
$this.find('.main').stop(true,true).animate({
left: '150%'
}, 200);
}, 2000);
$(this).data('timeout', timeoutHandle);
});
来源:https://stackoverflow.com/questions/23922264/jquery-animate-goes-bananas-despite-stop