为多个猫头鹰轮播创建计数器

时间:2019-03-07 08:30:35

标签: javascript php jquery owl-carousel

我需要创建多个owl carousel滑块,即使添加了多个滑块,我也需要使它在全局上都是相同的,直到我需要一个滑块上的计数器时,这才起作用。

因此,每个滑块都有一个计数器(1/5或1/9),该计数器在滚动或单击导航按钮时会发生变化

这里是我所拥有的,但是计数器坏了,它不能独立工作。

renderPlot

这是我的FIDDLE

1 个答案:

答案 0 :(得分:2)

说明:

实际上,您确定当前位置的方式很好。问题是使用计数器信息更新正确的div。

在您的小提琴中,您似乎正在搜索.counter,但是您应该搜索的是.counter,它是轮播容器的子代。

解决方案:

$(element).parent().find('.counter').html("item " + item + " of " + items)

工作示例:

$(function() {
  var owl = $('.owl-carousel');
  owl.owlCarousel({
    autoplay: 2000,
    items: 1,
    nav: true,
    loop: true,
    onInitialized: counter, //When the plugin has initialized.
    onTranslated: counter //When the translation of the stage has finished.
  });

  function counter(event) {
  	  
    var element = event.target; // DOM element, in this example .owl-carousel
    var items = event.item.count; // Number of items
    var item = event.item.index + 1; // Position of the current item

    // it loop is true then reset counter from 1
    if (item > items) {
      item = item - items
    }
    $(element).parent().find('.counter').html("item " + item + " of " + items)
  }
});
.container {
  width: 350px;
  margin: 15px auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.1.6/assets/owl.carousel.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.1.6/owl.carousel.min.js"></script>

<div class="container">
  <div class="owl-carousel">
    <!-- 4 items -->
    <div class="slides"><img src="https://unsplash.it/400/300/?image=121" alt="img1" /></div>
    <div class="slides"><img src="https://unsplash.it/400/300/?image=232" alt="img1" /></div>
    <div class="slides"><img src="https://unsplash.it/400/300/?image=343" alt="img1" /></div>
    <div class="slides"><img src="https://unsplash.it/400/300/?image=454" alt="img1" /></div>
  </div>
  <div class="counter"></div>
</div>
<br><br>
<div class="container">
  <div class="owl-carousel">
    <!-- 3 items -->
    <div class="slides"><img src="https://unsplash.it/400/300/?image=121" alt="img1" /></div>
    <div class="slides"><img src="https://unsplash.it/400/300/?image=232" alt="img1" /></div>
    <div class="slides"><img src="https://unsplash.it/400/300/?image=343" alt="img1" /></div>
  </div>
  <div class="counter"></div>
</div>