当幻灯片更改时,如何获取当前幻灯片的索引?

时间:2018-05-09 02:07:32

标签: javascript swiper

我有以下

mySwiper = new Swiper('.my-swiper', {
    direction: 'vertical',
    loop: true,
});
mySwiper.on('slideChange', function () {
    console.log('*** mySwiper.realIndex', mySwiper.realIndex);
});

但是realIndex总是返回上一个索引。因此,如果我在第一张幻灯片(0)上转到下一张幻灯片,那么当{1}}为0时,realIndex为0.当我回到第一张幻灯片时realIndex为1时应该是0.所以似乎事件在索引更新之前触发。我尝试了其他活动,但没有运气。是否有一个事件在更改幻灯片后触发,以便我可以捕获当前的幻灯片索引?

2 个答案:

答案 0 :(得分:2)

您应该使用transitionEnd事件,因为事件将在转换后触发。

见下面的演示



var mySwiper = new Swiper('.swiper-container', {
  direction: 'vertical',
  loop: true,
});
mySwiper.on('transitionEnd', function() {
  console.log('*** mySwiper.realIndex', mySwiper.realIndex);
});

.swiper-container {
  width: 100%;
  height: 100%;
}

.as-console-wrapper {
  z-index: 999999 !important;
}

.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;
  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
}

<!-- Link Swiper's CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.6/css/swiper.min.css">
<!-- Swiper -->
<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    <div class="swiper-slide">Slide 4</div>
    <div class="swiper-slide">Slide 5</div>
    <div class="swiper-slide">Slide 6</div>
    <div class="swiper-slide">Slide 7</div>
    <div class="swiper-slide">Slide 8</div>
    <div class="swiper-slide">Slide 9</div>
    <div class="swiper-slide">Slide 10</div>
  </div>
</div>

<!-- Swiper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.2.6/js/swiper.min.js"></script>
&#13;
&#13;
&#13;

注意:如果您无法在代码段中看到console.log语句输出,请使用F12查看幻灯片的索引。

答案 1 :(得分:0)

根据API,有一个事件slideChangeTransitionEnd,“......将动画播放到其他幻灯片(下一个或上一个)”。这听起来像是一个很有希望的事件而不是slideChange

http://idangero.us/swiper/api/