我有以下代码:
left = $('.academy-container').css('marginLeft');
function loop_forward(){
$('.academy-container').stop().animate(
{
marginLeft:'-=20'
},
{
duration: 100,
step: function(now, fx) {
left = fx.pos;
}
},
loop_forward
);
}
$('.carousel-next').hover(function() {
loop_forward()
}, function() {
stop();
})
}
我正在尝试使用 step 函数通过每一步更新“left”变量来跟踪边距向左移动的情况。但是,它并没有像我想象的那样工作。它没有继续动画,而是在 1 帧后停止。
我希望它不断循环播放动画,同时更新变量。我找不到此代码有什么问题,因此将不胜感激。 :)
谢谢。
编辑:这是我遇到的问题的一小部分: http://jsfiddle.net/RhQrV/1/
最佳答案
From your question: However, it's not quite working how I thought it would. Instead of continuing the animation, it stops after 1 frame.
From your comments: I want be able to hover on an element, and have it keep moving
您的动画工作正常,left 变量正在正确且持续更新。
但是,您的动画配置为在 100 毫秒的持续时间内仅将元素移动 20 个像素。当然,它几乎会立即停止 - 它完全按照它的指示进行。
如果想让动画持续运行,可以使用动画的complete事件来调用自身。 Here's a jsFiddle .我在这里修改了 mouseout 函数以结束动画:
$('.hover').hover(function() {
loop_forward();
}, function() {
$('.academy-container').stop(); // Stops the element's animation
});
动画的配置现在看起来也是这样的:
{
easing: 'linear', // Ensure a smooth animation
step: function (now, fx) {
left = fx.pos;
console.log(left);
},
complete: loop_forward // Animation now loops itself
}
关于jQuery animate step() 停止动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158413/