Javascript setInterval()是否使动画在加载时开始?
我有一个转盘的jQuery代码,但它并没有像我想象的那样工作Javascript setInterval()是否使动画在加载时开始?,javascript,jquery,Javascript,Jquery,我有一个转盘的jQuery代码,但它并没有像我想象的那样工作 var totalItems = $('.inner li').length, currentItem = 1, $inner = $('.inner li'), width = $inner.outerWidth(true);
var totalItems = $('.inner li').length,
currentItem = 1,
$inner = $('.inner li'),
width = $inner.outerWidth(true);
setInterval(function() {
$inner.animate({
right: '+=' + width
}, 500);
currentItem += 1;
}, 500);
您可以在此处查看示例
提前谢谢
编辑:
这是我为另一个旋转木马工作的全部代码
$(document).ready(function() {
var totalItems = $('.inner li').length,
currentItem = 1,
$inner = $('.inner li'),
width = $inner.outerWidth(true),
speed = 400,
delay = 4000;
var timer = setInterval(function() {
if (currentItem === totalItems) {
$inner.animate({
right: '-=' + width * (totalItems-1) + 'px'
}, speed);
currentItem = 1;
} else {
$inner.animate({
right: '+=' + width
}, speed);
currentItem += 1;
}
}, delay);
$('.carousel').hover (function(ev) {
clearInterval(timer);
}, function(ev){
timer = setInterval(function() {
if (currentItem === totalItems) {
$inner.animate({
right: '-=' + width * (totalItems-1) + 'px'
}, speed);
currentItem = 1;
} else {
$inner.animate({
right: '+=' + width
}, speed);
currentItem += 1;
}
}, delay);
});
$('#right').click(function () {
if (currentItem === totalItems) {
$inner.animate({
right: '-=' + width * (totalItems-1) + 'px'
}, speed);
currentItem = 1;
} else {
$inner.animate({
right: '+=' + width,
}, speed);
currentItem += 1;
}
});
$('#left').click(function () {
if (currentItem === 1) {
$inner.animate({
right: '+=' + width * (totalItems-1) + 'px'
}, speed);
currentItem = totalItems;
} else {
$inner.animate({
right: '-=' + width
}, speed);
currentItem -= 1;
}
});
})) 不,没有
它只是设置了一个调用传递函数的时间间隔,所以如果你将500毫秒作为一个时间间隔传递,函数将从现在起(大约)500毫秒被调用,然后从现在起(大约)1秒,然后
setInterval也与页面加载无关,如果这是您的意思的话(例如,它不依赖于主体加载或类似的内容,而是依赖于它被执行的时刻)
我之所以这么说,是因为浏览器的计时不是很精确(有几个原因)。此外,您应该将setInterval的返回值保存在一个变量中,并确保在不再需要时清除该间隔。根据浏览器的不同,这通常是在页面卸载时自动完成的,但在某些较旧的浏览器上,这可能在浏览器关闭之前不会发生
编辑:看看小提琴,你的问题是css,而不是javascript。您的
li
需要定位为相对的
或绝对的
,否则设置右
属性将无效。您还可以设置margin right
/margin left
间隔有效,无效的是您的标记和逻辑“我认为应该”。。。它应该如何工作?每隔500毫秒,通过整个UL
width?@RokoC.Buljan设置动画,我的代码的目标是li
width,不是吗?请参阅我的更新答案-尝试设置位置:绝对打开。内部li,您将看到移动。这只是向您展示总体方向,因为您的布局将不是您想要的位置:Absolute我将我的更新为工作转盘的代码,但当我添加到此页面时,它不起作用。@AndresRivera更新了答案。你的问题是css,而不是js。我也在看我的css。溢出:隐藏代码>不适用于我的.carousel
类。我应该在旋转木马周围加一个包装吗?@AndresRivera position:absolute和overflow:hidden不能很好地配合,但是如果你使用右边距/左边距或position:relative,它应该可以在溢出不可见的情况下工作。谢谢@griffin,我还想知道为什么我的问题会得到反对票?只是想知道。