首页 > 解决方案 > 如何在 if 条件下使用“swiper.activeIndex”?

问题描述

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

我如何使用swiper.activeIndex条件if

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

标签: javascriptjqueryhtmlswiper

解决方案


嗨,您需要做的是监听您的 swiper 的“slideChange”事件。

要了解有关 swiper 的事件和 api 的更多信息,请查看文档:https ://idangero.us/swiper/api/

下面是一个关于如何做到这一点的简短示例:

<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>


推荐阅读