[英]jQuery toggle Class on multiple Elements with interval
I've created this little fancy jQuery Snippet to toggle the class of an element in an interval: 我创建了这个小巧的jQuery代码段,以在一个间隔中切换元素的类:
setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800);
The script works fine! 脚本工作正常! Now I got multiple elements with the base-class .slide-image
in the wrapper .grid-item
. 现在,包装器.grid-item
具有基类.slide-image
多个元素。
<div class="grid-item">
<div class="slide-image"><img src="http://www.placehold.it/500x500/233953"></div>
<div class="slide-image"><img src="http://www.placehold.it/500x500/03144b"></div>
<div class="slide-image"><img src="http://www.placehold.it/500x500/030a4b"></div>
</div>
Is there a way to rewrite the snippet so the second .slide-image
gets the class .active
after the first one? 有没有办法重写代码段,以便第二个.slide-image
在第一个之后获得类.active
? Then the third element and so on... 然后是第三个元素,依此类推...
The Problem: The amout of .slide-image
-elements is no defined. 问题: .slide-image
定义尚未定义。 In some cases there are two of them, in another there are four elements. 在某些情况下,其中有两个,在另一些情况下,则有四个要素。
Try this 尝试这个
var slides = $('.grid-item .slide-image'), // cache slides
counter = 0; // global counter
setInterval(function(){
slides.removeClass('active'); // remove active class
slides.eq(counter).addClass('active'); // add active class
counter++;
if (counter == slides.length) counter = 0; // reset counter after last slide
}, 800);
You can check if current active element id last or not. 您可以检查当前活动元素ID是否最后。 if it is, then show first element in set else show next sibling element: 如果是,则显示set中的第一个元素,否则显示下一个同级元素:
$(function(){
var slides = $('.grid-item .slide-image');
setInterval(function(){
var currentactive = $('.active');
var _target = currentactive.is(':last-child') ? slides.first() : currentactive.next();
slides.removeClass('active')
_target.addClass('active')
}, 800);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.