当前位置: 代码迷 >> 综合 >> 控制Swiper切换到指定swiper-slide
  详细解决方案

控制Swiper切换到指定swiper-slide

热度:93   发布时间:2023-11-04 22:14:57.0

背景:

    移动端产品列表页,产品类别横向滚动展示,如下图选中 "类别4"跳转加载新数据,swiper滚动一定距离使"类别4"居中显示。

html:

 <div class="product-menu clear swiper-container"><div class="swiper-wrapper"><div class="swiper-slide product-menu-list" style="width: auto!important;"><a href="/product/index.html?catid=2" data-catid="0">全部</a></div><div class="swiper-slide product-menu-list" style="width: auto!important;"><a href="/product/index.html?catid=3" data-catid="0">类别1</a></div><div class="swiper-slide product-menu-list" style="width: auto!important;"><a href="/product/index.html?catid=4" data-catid="0">类别2</a></div><div class="swiper-slide product-menu-list" style="width: auto!important;"><a href="/product/index.html?catid=5" data-catid="0">类别3</a></div><div class="swiper-slide product-menu-list" style="width: auto!important;"><a href="/product/index.html?catid=6" data-catid="0">类别4</a></div></div></div>

js:

   window.onload = function() {var swiper = new Swiper('.swiper-container', {slidesPerView: 'auto',freeMode:true,});var index = "{$index}"; // index为指定将要切换到的slide的索引swiper.slideTo(index, 100, false);     };
ps: 可参考官方文档 https://www.swiper.com.cn/api/methods/109.html

 

  相关解决方案