1
//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.ready5 秒。

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

4

1 回答 1

6

您可以调用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);
};
于 2012-11-10T07:15:32.383 回答