我有一个旋转木马的jQuery代码,但它没有像我想的那样工作。
var totalItems = $('.inner li').length,
currentItem = 1,
$inner = $('.inner li'),
width = $inner.outerWidth(true);
setInterval(function() {
$inner.animate({
right: '+=' + width
}, 500);
currentItem += 1;
}, 500);
您可以在此FIDDLE
查看示例提前致谢。
修改 这是我为另一个轮播工作的整个代码。
$(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;
}
});
});
答案 0 :(得分:1)
不,它没有。
它只是设置调用传递函数的间隔,所以如果你传递500ms作为一个间隔,函数将从现在开始调用(大约)500ms,然后(大约)从现在开始调用1秒,然后..
setInterval也与页面加载无关,如果这是你的意思(例如它不依赖于身体负载或类似的东西,但它会被执行的那一刻)
我说 about 因为浏览器时间不是很精确(出于几个原因)。此外,您应该将setInterval的返回值保存在变量中,并确保在不再需要时清除间隔。根据浏览器的不同,这通常会在页面卸载时自动完成,但在某些较旧的浏览器上,可能不会在浏览器关闭之前完成。
编辑:看着小提琴,你的问题是用css,而不是用javascript。您的li
需要定位relative
或absolute
,否则设置right
属性将无效。您还可以设置margin-right
/ margin-left
。