问题
I have created a div to slide in from outside of the viewport and place itself over the original div.
The animation is triggered by hovering over box1
. This will bring box2
in place of box1
.
When the mouse leaves the box2
div, it will be placed outside of the viewport again.
However, slow cursor movement within this div will result in animation triggering rapidly.
$(document).ready(function() {
$('.box1').mouseover(function() {
$('.box2').stop().animate({
top: 0
}, 100);
}).mouseout(function() {
$('.box2').stop().animate({
top: '-200px'
}, 100);
});
});
The following fiddle should present the problem.
http://jsfiddle.net/B9wx8/
回答1:
Do like this, Bind event for both elements, it would solve the issue
$(document).ready(function () {
$('.box1,.box2').mouseenter(function () {
$('.box2').stop().animate({
top: 0
}, 'slow');
}).mouseleave(function () {
$('.box2').stop().animate({
top: '-200px'
}, 'slow');
});
});
DEMO
回答2:
You could do something like this:
var done = true;
$(document).ready(function() {
$('.box1').mouseenter(function() {
if (done){
done = false;
$('.box2').stop().animate({
top: 0
}, {duration: 400,
complete:
function(){
done = true
}
});
}
});
$('.box2').mouseleave(function() {
if (done){
done = false;
$('.box2').stop().animate({
top: -400
}, {duration: 400,
complete:
function(){
done = true
}
});
}
});
});
So check if the animation is still going, and only if not start the next one
来源:https://stackoverflow.com/questions/24712501/jquery-animation-transition-interrupted-by-hover