swiper5切換頁面數據動態加載

如果本文幫助到你,本人不勝榮幸,如果浪費了你的時間,本人深感抱歉。
如果有什麼錯誤,請一定指出,以免誤導大家、也誤導我。

swiper官方網址:點擊查看

線上demo:點擊查看

核心方法,在當前Slide切換到另一個Slide時執行:

<script language="javascript"> 
var mySwiper = new Swiper('.swiper-container',{
  on:{
    slideChange: function(){
      alert('改變了,activeIndex爲'+this.activeIndex);
    },
  },
})
</script>

詳見:https://www.swiper.com.cn/api/event/405.html

完整代碼:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
    integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://unpkg.com/swiper/css/swiper.min.css">
  <script src="https://unpkg.com/swiper/js/swiper.min.js"> </script>
</head>

<body>
  <div class="swiper-container temp">
    <div class="swiper-wrapper">
      <div class="swiper-slide">
        1
      </div>
      <div class="swiper-slide">
        2
      </div>
      <div class="swiper-slide">
        3
      </div>
    </div>
  </div>
</body>
<script>
  var now_ActiveIndex = 2; //,//當前所在下標
  var tempSwiper = new Swiper('.swiper-container.temp', {
    initialSlide: 1,
    loop: true,
    speed: 400,
    on: {
      slideChange: function (swiper) { //當前Slide切換時執行(activeIndex發生改變)
        var pre_number = Number($(this.slides[now_ActiveIndex]).text()); //獲取當前頁數字
        if (now_ActiveIndex > this.activeIndex) { //如果當前數字大於索引,索引區間範圍1~4
          if (now_ActiveIndex == 4 && this.activeIndex == 1) { //swiper回到第一頁
            $(this.slides[this.activeIndex]).text(pre_number);
          } else { //上一個
            var act_number = pre_number - 1;
            $(this.slides[this.activeIndex]).text(act_number);
          }
        } else if (now_ActiveIndex < this.activeIndex) {
          if (now_ActiveIndex == 0 && this.activeIndex == 3) {
            $(this.slides[this.activeIndex]).text(pre_number);
          } else { //下一個
            var act_number = pre_number + 1;
            $(this.slides[this.activeIndex]).text(act_number);
          }
        }
        now_ActiveIndex = this.activeIndex;
      },
    },
  })
</script>
<style>
.temp{
  width: 100%;
  height: 200px;
  background: #ccc;
}
.swiper-slide{
  display: block;
  width: 100%;
  height: 100%;
  text-align: center;
  line-height:200px;
  font-size: 30px;
}
</style>

</html>

如要模擬異步請求,可使用mySwiper.allowSlideNext,mySwiper.allowSlidePrev,mySwiper.allowTouchMove配合使用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章