javascript - 循环动画javascript,SetInterval只工作一次

标签 javascript jquery html jquery-animate

我正在使用 JavaScript 尝试为 div 制作动画。出于某种原因,我的 div 没有每 2 秒循环向右 400px,它只移动一次。

JavaScript:

<script>
    function animate(name,dist,time) {
        $(name).animate({left:dist},time);
    }
    $(function() {
        setInterval(animate('.box1',400,800),2000);
    });
</script>  

HTML:

<div class="box1"></div>

最佳答案

试试这个

function animate(name,dist,time) {
    $(name).animate({left:dist},time);
}
$(function() {
    setInterval(
        function() {
            animate('.box1',"+=400",800)
        },
        2000
    );
});

您可以在这里进行测试:https://jsfiddle.net/CliffBurton/k03cyup1/ (我使用 50px 只是为了测试)

jQuery animate() 函数的属性可以是相对的。

If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

在这里你可以找到 jQuery animate() function reference

关于javascript - 循环动画javascript,SetInterval只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35113170/

相关文章:

javascript - 显示/隐藏内容不适用于 IE10 及以下版本。 Div不可点击

javascript - 如何使用 Jasmine 检查对象是否包含项目

javascript - 在单独的 Div 中加载相同的代码两次

javascript - 使用 Jquery 隐藏跨度匹配条件中的所有字符串

javascript - 默认在弹出窗口中打开 HTML 文件

javascript - 在 ReactJS 中渲染 2 个表行

javascript - 为什么在编译另一个指令时需要一个scope.$apply?

jquery - 为什么 sammy.js 从不使用 post 路由?

javascript - 为什么jQuery会滑下来破坏我在Chrome中的嵌入式YouTube播放器?

javascript - 如何制作变换动画