更改类每隔几秒钟从数组的值 [英] Change class every few seconds from values in array
问题描述
我试图改变每3秒一个div类。类是在阵列中,previous类应该被删除,下一个补充。 第一应该是第一个,那么第二,那么第三,并回到循环。
I am trying to change class on a div every 3 seconds. Classes are in array, previous class should be removed and next one added. "First" should be first, then "second", then "third" and back to loop.
我知道如何 addClass('东西')
但我被困在部分,其中code应该把下一个可用的类从数组。
I know how to addClass('something')
but I am stuck on part where code should put the next available class from array.
<div id="main"></div>
jQuery(document).ready(function ($) {
var images = ['first', 'second', 'third'];
function changeBackground() {
var className = $('#main').attr('class');
if (className == null)
className = images[0];
$('#main').removeClass(function () {
var newClass = // find value in array and take next value, if end of array get first
$(this).addClass(newClass);
});
}
changeBackground();
setInterval(changeBackground, 2000);
});
https://jsfiddle.net/skd636fc/3/
推荐答案
您不需要传递一个函数到 removeClass移除
。你需要跟踪你在这样你就可以移动到下一个的下一个计时器滴答什么课。我在评论中解释说:
You don't need to pass a function into removeClass
. You do need to keep track of what class you're on so you can move to the next on the next timer tick. I've explained in the comments:
jQuery(document).ready(function($){
var images = ['first', 'second', 'third'];
// Remember where we are in the array, start just before the first entry
var classIndex = -1;
function changeBackground() {
// Grab the element
var main = $("#main");
// If this isn't the first time, remove the previous class
if (classIndex >= 0) {
main.removeClass(images[classIndex]);
}
// Update the index, wrapping around when we reach the end of the array
classIndex = (classIndex + 1) % images.length;
// Add the new class
main.addClass(images[classIndex]);
}
changeBackground();
setInterval(changeBackground, 2000);
});
有关上述注意事项:
Notes about the above:
- 这显然更加紧凑而不解释性意见
- 它不会消灭其他不相关的类对
#main
(而使用removeClass移除()解决方案
与没有参数会)
- It's obviously much more compact without explanatory comments
- It won't wipe out other, unrelated classes on
#main
(whereas solutions usingremoveClass()
with no arguments will)
下面是一个更紧凑的版本,如果你到那种事。我不会建议它压缩到相当这种程度,虽然。 : - )
Here's a more compact version if you're into that kind of thing. I wouldn't suggest compacting it to quite this degree, though. :-)
jQuery(document).ready(function($){
var classIndex = 0, images = ['first', 'second', 'third'];
$("#main").addClass(images[classIndex]);
setInterval(function () {
$("#main")
.removeClass(images[classIndex])
.addClass(images[classIndex = (classIndex + 1) % images.length]);
}, 2000);
});
这篇关于更改类每隔几秒钟从数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!