如何在if条件下使用“ swiper.activeIndex”?

时间:2019-07-24 04:59:51

标签: javascript jquery html swiper

我在我的项目中使用Swiper.js。我想知道当前的活动滑块。

如何在swiper.activeIndex条件下使用if

或者,我想为到达预期的滑块编写一些代码。

1 个答案:

答案 0 :(得分:1)

您好,您需要做的是监听滑水器的“ slideChange”事件。

要了解有关事件和swiper的api的更多信息,请查看文档:{​​{3}}

这里有一个简短的示例:

<script>
var swiper = new Swiper('.swiper-container');
    swiper.on('slideChange', function () {
        if(this.activeIndex === 1) {
            console.log("IM ON SECOND SLIDE!");
            alert("IM ON SECOND SLIDE!");
        }
    });

</script>

完整的示例(从演示页面获取代码):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Swiper demo</title>
  <!-- Link Swiper's CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.min.js"></script>
  <!-- Demo styles -->
  <style>
    html, body {
      position: relative;
      height: 100%;
    }
    body {
      background: #eee;
      font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
      font-size: 14px;
      color:#000;
      margin: 0;
      padding: 0;
    }
    .swiper-container {
      width: 100%;
      height: 100%;
    }
    .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;
    }
  </style>
</head>
<body>
  <!-- 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>

  <!-- Initialize Swiper -->
  <script>
    var swiper = new Swiper('.swiper-container');
    swiper.on('slideChange', function () {
      if(this.activeIndex === 1) {
        console.log("IM ON SECOND SLIDE!");
        alert("IM ON SECOND SLIDE!");
      }
    });
		
  </script>
</body>
</html>