//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/