javascript - 在 javascript 或 jquery 中延迟一个就绪的 function()

标签 javascript jquery

//this code animates the divs to the left after every 5 secs
$(document).ready(function() {

    var refreshId = setInterval(function() {
        $('.box').each(function() {
            if ($(this).offset().left < 0) {
                $(this).css("left", "150%");
            } else if ($(this).offset().left > $('#container').width()) {
                $(this).animate({
                    left: '50%'
                }, 500);
            } else {
                $(this).animate({
                    left: '-150%'
                }, 500);
            }
        });
    }, 5000);)
};​

在上面的代码中,每当页面加载时,div 元素就会每 5 秒滑动一次。但是我的网页中有一个按钮,单击该按钮时,会根据单击的按钮分别向左或向右移动 div 元素。但问题是自动动画和点击按钮时出现的动画有时会重叠。因此,每当我单击按钮时,我都想将 document.ready 中的自动动画再次延迟 5 秒。

这显示在这个 jsFiddle 中.当您一直点击“左动画”或“右动画”按钮时,div 有时会重叠。所以我只想在单击按钮时延迟自动动画。

最佳答案

您可以调用 clearInterval(refreshId),然后重新运行您的代码以设置轮换。

这是您如何操作的粗略草图。恐怕我无法提供比这更详细的信息,但希望对您有所帮助!

$(document).ready(function () {
    var refreshId;
    function startRotation() {
        refreshId = setInterval(function () { /* rotate stuff */ }, 5000);
    }
    function restartRotation() {
        clearInterval(refreshId);
        startRotation();
    }
    startRotation();

    var button = /* find the buttons that should restart the rotation */;
    button.click(restartRotation);
};

关于javascript - 在 javascript 或 jquery 中延迟一个就绪的 function(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13320108/

相关文章:

javascript - 单独上传多个文件

javascript - 在 href 点击上使用动画功能

javascript - 正在阅读 attr 类,但我只需要其中之一

forms - Rails,在下拉列表中选择选项会过滤第二个下拉列表中的值

javascript - 如何使用 JQuery 验证正则表达式不需要的字段

javascript - 按钮的绝对位置居中但现在全宽

javascript - 如何清空一个对象,它是javascript中数组的元素

javascript - 更改运行时 jquery 的 id 属性

javascript - ES6 : constructor can't declare as arrow function?

javascript - WebGL VS Canvas 二维硬件加速