我正在尝试创建轮播效果,但是我的循环仅返回数组内的最后一个值。我想在特定时间后遍历每个项目。这是带有代码的codepen。
$(function() {
//var timer = 3000;
var $items = $('img', '.container');
var currentIdx = 0;
var cycleItems = function() {
console.log('Running from cycleItems');
var item = [];
for (let i = 0; i < $items.length; i++) {
var item = $items[i];
setTimeout(function() {
console.log('We are at this item: ${item}');
console.log('And we are at this index: ' + currentIdx);
if ($(item).hasClass('isHidden')) {
$(item).removeClass('isHidden').addClass('isActive')
}
currentIdx++
}, 3000);
}
}
/*$item.removeClass('isHidden').addClass('isActive).setTimeout(function() { $( this ).animate( { scrollLeft: 200 + 'px' } ), '500', 'swing', function() { console.log('Animation completed') } }) */
cycleItems();
});
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
background: black;
}
.container {
display: inline;
//border: 1px solid white;
}
.slide {} .isActive {
visibility: visible;
}
.isHidden {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=container>
<img class='isActive' src="http://placehold.it/350x150">
<img class='isHidden' src="http://placehold.it/350x150">
<img class='isHidden' src="http://placehold.it/350x150">
<img class='isHidden' src="http://placehold.it/350x150">
</div>
最佳答案
尝试这个:
$(function() {
//var timer = 3000;
var $items = $('img','.container');
var currentIdx = 0;
var cycleItems = function() {
console.log('Running from cycleItems');
$items.each(function(index, item){
setTimeout(function() {
console.log(`We are at this item: ${index}`);
console.log('And we are at this index: ' + currentIdx );
$(item).removeClass('isHidden').addClass('isActive')
/*if ( $(item).hasClass('isHidden') ) {
} */
currentIdx++
}, 3000*index);
});
}
/*$item.removeClass('isHidden').addClass('isActive).setTimeout(function() { $( this ).animate( { scrollLeft: 200 + 'px' } ), '500', 'swing', function() { console.log('Animation completed') } }) */
cycleItems();
});
重要的是将计时器与索引相乘,否则计时器将只工作一次。