我想让一个 div 在某个区域内水平来回动画。我现在遇到的问题是我不知道如何让我的 div 在向前移动后向后移动。
这是我正在使用的脚本:
<script type="text/javascript">
var animatethis = function (targetElement, speed) {
$(targetElement).animate(
{
marginLeft: "+=250px"
},
{
duration: speed,
complete: function () {
animatethis(this, speed);
animatethis.stop();
$(targetElement).animate({ marginLeft: "-=250px" });
}
}
)
};
animatethis($('#q1'), 5000);
</script>
最佳答案
查看浏览器控制台。 animatethis
不返回任何内容,这意味着该行
animatethis.stop();
总是会崩溃(类似于“TypeError:无法调用未定义的方法‘stop’”)。您还混淆了 complete
回调中动画的顺序。
停下来,深呼吸,想想上面的代码实际上在做什么。
<小时/>好的,所以在增加 marginLeft
后,您想要减少它。 那么你想从头开始。正确的?所以:
function animatethis(targetElement, speed) {
$(targetElement).animate({ marginLeft: "+=250px"},
{
duration: speed,
complete: function ()
{
targetElement.animate({ marginLeft: "-=250px" },
{
duration: speed,
complete: function ()
{
animatethis(targetElement, speed);
}
});
}
});
};
animatethis($('#q1'), 5000);
还有很多其他方法可以给这只猫剥皮,但这确实有效。 http://jsfiddle.net/mattball/rKu6Y/
关于jquery - 如何使用jquery的animate方法让div来回移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9442409/