Cycle 'active' Class with Carousel

血红的双手。 提交于 2019-12-24 15:58:47

问题


I have a carousel with nine slides, the first of which has a class of 'active'.

<ul class='nav'>
    <li class='left'>left</li>
    <li class='right'>right</li>
</ul>

<ul class='carousel'>
    <li class='active'></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

When the 'right' button is clicked, the active class needs to move to the next li (it also needs to be applied back to the first li after the last one).

And obviously, the active class needs to move in the opposite direction when the left button is clicked.

I tried the following, which works up to a point, but I don't know how to make the active class go back to the first li after the last one.

$('.nav .right').click(function(){
    $('.carousel .active').removeClass('active').next().addClass('active');
});

Any help would be appreciated. Thanks.


回答1:


It could certainly be improved, but the following code works for what you need to do:

$('.nav .right').click(function(){
    var next = $('.carousel .active').removeClass('active').next();
    if (next.length == 0) { next = $('.carousel li').first(); }
    next.addClass('active');
});



回答2:


$('.nav .right').click(function () {
    $('.carousel .active:not(:last-child)').removeClass('active').next().addClass('active');
});
$('.nav .left').click(function () {
    $('.carousel .active:not(:first-child)').removeClass('active').prev().addClass('active');
});

FIDDLE




回答3:


Try

var $carousel = $('.carousel');
$('.nav .right').click(function(){
    var next = $carousel.children('.active').removeClass('active').next();
    if(!next.length){
        next = $carousel.children().first();
    }
    next.addClass('active');
});

$('.nav .left').click(function(){
    var prev = $carousel.children('.active').removeClass('active').prev();
    if(!prev.length){
        prev = $carousel.children().last();
    }
    prev.addClass('active');
});

Demo: Fiddle

Another variation: Fiddle



来源:https://stackoverflow.com/questions/17672261/cycle-active-class-with-carousel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!