如何在Owl Carousel 2的可见项目中的第一个和最后一个项目中添加课程?

时间:2016-10-18 10:22:10

标签: jquery html css css3 owl-carousel

我需要在Owl Carousel 2的当前可见项目的第一个和最后一个项目中添加一个类。

3 个答案:

答案 0 :(得分:5)

<强>样本:

http://plnkr.co/edit/t9URfKq9Mwh9jO705h7u?p=preview

猫头鹰轮播为所有可见项添加了一个活动类。所以你可以看到我在下面编写了一个脚本来循环遍历所有活动类的owl-item,然后使用第0个和最后一个索引,我添加了两个不同的类。

使用项目中的代码,您将添加类。

jQuery(document).ready(function($) {

    var carousel = $(".latest-work-carousel");
    carousel.owlCarousel({
        loop : true,
        items : 3,
        margin:0,
        nav : true,
        dots : false,
    });

    checkClasses();
    carousel.on('translated.owl.carousel', function(event) {
        checkClasses();
    });

    function checkClasses(){
        var total = $('.latest-work-carousel .owl-stage .owl-item.active').length;

        $('.latest-work-carousel .owl-stage .owl-item').removeClass('firstActiveItem lastActiveItem');

        $('.latest-work-carousel .owl-stage .owl-item.active').each(function(index){
            if (index === 0) {
                // this is the first one
                $(this).addClass('firstActiveItem');
            }
            if (index === total - 1 && total>1) {
                // this is the last one
                $(this).addClass('lastActiveItem');
            }
        });
    }


});

<强>样本:

http://plnkr.co/edit/t9URfKq9Mwh9jO705h7u?p=preview

答案 1 :(得分:1)

我在设置最后一个活动项目方面也遇到了同样的问题,并且找不到任何方便的修复方法。最后提出了一个适合我的修复程序。

这是一个对我有用的简单修复。

$('.owl-carousel')
  .on('changed.owl.carousel initialized.owl.carousel', function(event) {
    $(event.target)
      .find('.owl-item').removeClass('last')
      .eq(event.item.index + event.page.size - 1).addClass('last');
  }).owlCarousel({
    responsive: {
      0: {
        items: 3,
      },
      768: {
        items: 4,
      },
    }
  });

只需使用css即可轻松设置第一项。

.owl-item:not(.active) + .owl-item.active{
   background: red;  
}

答案 2 :(得分:0)

按照@Lasithds 的回答,如果您想将“active”类添加到第一个 owl 活动 div,您可以使用以下内容:

$('.owl-carousel').on('changed.owl.carousel initialized.owl.carousel', function (event) {
    $(event.target)
        .find('.owl-item').removeClass('first')
        .eq(event.item.index).addClass('first');
})
.owlCarousel({
    loop: false,
    dots: false,
});