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{
   100%;
  height: 200px;
  background: #ccc;
}
.swiper-slide{
  display: block;
   100%;
  height: 100%;
  text-align: center;
  line-height:200px;
  font-size: 30px;
}
</style>
 
</html>

如要模拟异步请求,可使用mySwiper.allowSlideNext,mySwiper.allowSlidePrev,mySwiper.allowTouchMove配合使用。

原文地址:https://www.cnblogs.com/linfblog/p/12147393.html