jquery - 如何使用jquery的animate方法让div来回移动

标签 jquery jquery-animate

我想让一个 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/

相关文章:

javascript - 如何删除/禁用appendTo元素上的提交?

javascript - 如何通过自动填充表格来获取以年、月和日为单位的年龄?

javascript - 在表格标题中绘制日历

javascript - Jquery移动对象

javascript - 悬停时的 Jquery 颜色随机化

javascript - 一旦满足特定条件就停止动画 - Jquery

javascript - 动画将最后一个 child 附加到第一个

jquery - 在 Jquery 中为 .animate 设置边界

javascript - 检查元素是否正在动画 CSS3

JavaScript 正则表达式数字与包含单个零的字符串不匹配