swiper-居中当前选中项并且去除前后空白区域

1,059 阅读1分钟

业务背景:

一个可滑动区域多个tab项,点击选项居中

截图.png

首先安装swiper,并且在mounted初始化,如果数据依赖异步请求记得await一下


let that = this 
// eslint-disable-next-line no-new 
new Swiper('.swiper-container', { 
    slidesPerView: 3 
})

设置slider容器能够同时显示的slides数量(slidesPerView),超出滚动

网上现在给出的居中方案大多是centeredSlides设置为true,但这会造成首尾空白,如图:

截图 (1).png

解决方案是,点击slide的时候,根据索引手动设置transform

handleListTab (val, index) {
      this.currentListTab = val.value
      this.getLeaderboardList()
      if (index > 0 && index < this.databaseList.length - 1) {
        this.setTranslate(document.querySelector('.swiper-slide').offsetWidth * -(index - 1))
      }
    },
setTranslate (val) {
      document.querySelector('.swiper-wrapper').style.transform = `translate3d(${val}px, 0px, 0px)`
    },

当点击第一个与最后一个的时候不需要手动设置位移,其他的移动距离都是左侧模块数量 * 宽度,这样就能达到想要的效果了

文字功力较差,算是一个踩坑记录,希望能帮到有相同需求的uu