disabling animation while hovering
Below I have some code which basically animates a div from the bottom of the page to the top. When I hover over the div I want the animation to stop immediately and giv开发者_开发知识库e the div an opacity value of 0.25. When the mouse leaves the div I want the animation to continue.
Right now the animation doesn't stop and the opacity value is given after the animation is finished and not immediately which is what I want.
So how do I get the result I want?
<!DOCTYPE html>
<html>
<head>
<style>
#bubble{
border-radius:20px;
margin:3px;
width:40px;
height:40px;
position:absolute;
left:0px;
top:1000px;
background:green;
display:none;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="bubble"></div>
<script>
function runIt() {
$('#bubble').show(0);
$('#bubble').animate({top:'-=1000px',},5000);
$('#bubble').animate({top:'+=1000px',},0);
$('#bubble').hide("normal", runIt);
}
runIt();
$('#bubble').hover(function() {
$('#bubble').animate({
opacity: 0.25,
}, 500, function() {});
});
</script>
</body>
</html>
There's a jQuery pause/resume plugin that does exactly what your looking for.
See this fiddle as an example
You're looking for .stop()
. You could use that to stop any animations running on a selected element (and optionally make it instantaneously go to the animation's logical end) on the mouseover
and restart the animation on the mouseout
components of hover()
.
$('#bubble').animate({
// blah
}).hover(function() {
// stop animation
$(this).stop().css({ opacity : 0.25 });
}, function () {
// continue animation
$(this).css({ opacity : 1.0 }).animate({ /* blah */ });
});
However, looking at your code, you're using incremental animation (i.e. using +=1000px
instead of something fixed like 1000px
). Because of that, you'll have to keep track of the animation's progress somehow and apply an adjusted incremental on the mouseout
.
For example, if #bubble
is animating, and then you hover on it, you should be able to determine that it's already moved 300px
for example, and call an adjusted .animate({ top : '-=700px' })
on the continue.
If you were using fixed values for animation, it shouldn't be a problem to just call the original animation again on the continue.
In the hover event, you'll want to call .stop(true, false). Then in the exit function (currently empty), you'll need to restart the animation from the current position.
<script>
function runIt() {
$('#bubble').show(0);
$('#bubble').animate({top:'-=1000px'},5000);
$('#bubble').animate({top:'+=1000px'},0);
$('#bubble').hide("normal", runIt);
}
runIt();
$('#bubble').hover(function() {
$(this).stop(true, false);
$(this).animate({
opacity: 0.25,
}, 500);
}, function() {
runIt();
});
</script>
精彩评论