简体   繁体   English

jQuery将CSS类应用于下一个元素

[英]jQuery apply css class to next single element

I am trying to create a simple jquery slideshow. 我正在尝试创建一个简单的jquery幻灯片。 However I am having trouble getting it to loop through the elements. 但是我很难让它遍历所有元素。

I know next() just add's the active class to the next elements, and not a single. 我知道next()只是将活动类添加到下一个元素,而不是单个元素。 That is the part i am having trouble with. 那是我遇到麻烦的部分。 How can just apply a single class to the next element, and it loop forever. 如何仅将单个类应用于下一个元素,它就会永远循环。

jQuery(document).ready(function () {

var slides = jQuery('#slideshow'); //Parent container for the slideshow
var activeClass = 'active'; //Set the active slide CSS class
var interval = 3000; // Interval in miliseconds
var countSlides = slides.children().length;

//Runs the slideshow
function cycle() {
    slides.children().removeClass(activeClass);
    slides.children().next().addClass(activeClass);
};

setInterval(cycle, interval);
});

According to the documentation .next() returns the element next to every element in the collection it is called on. 根据文档, .next()返回在其被调用的集合中每个元素旁边的元素。 In your case that is all children. 您的情况就是所有孩子。 If you select only the current active element before dropping the .active class you can get the element next to it. 如果在删除.active类之前仅选择当前活动元素,则可以在该元素旁边获得该元素。

function cycle() {
    var $current = slides.children('.active');
    $current
        .removeClass('active')
        .next().addClass('active');
}

Edit: as on how to loop. 编辑:关于如何循环。 You need to check if there is a next element. 您需要检查是否存在下一个元素。 If .next() does not return a new element you could grab the first child instead: 如果.next()不返回新元素,则可以改为抓取第一个孩子:

var $current = slides.children('.active'),
    $next = $current.next();
if (!$next.length) {
   // No next slide, go back to the first one.
   $next = slides.children().first();
}
$current.removeClass('active');
$next.addClass('active');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM