swiper首尾两项不居中其余项居中

swiper的使用中有一种场景是首尾两项靠左或者靠右显示,其余项居中显示,如图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
如果所有项都居中并且露出相邻项的一部分,可直接如下设置:

const settings = {
  // 两遍显示相邻两张
  slidesPerView: 'auto',

  // 相邻两张间距
  spaceBetween: 12,

  // swiper动态加载
  observer:true, 
  observeParents:true,

  // 当前页居中显示
  centeredSlides: true,
}

首尾两张贴边,可以加一个参数:

const settings = {
  // 两遍显示相邻两张
  slidesPerView: 'auto',

  spaceBetween: 12,

  // swiper动态加载
  observer:true, 
  observeParents:true,

  // 当前页居中显示
  centeredSlides: true,

  // 第一张和最后一张贴合边缘 
  centeredSlidesBounds: true, 
}

然后在组件中new Swiper:

  useEffect(() => {
      let mySwiper = new Swiper('.swiper-container', settings);
      mySwiper.on('slideChange',hanldeSlide)
      return ()=>{
        mySwiper.destroy();
      }
  }, []);

需要设置.swiper-wrapper宽为100%,和滑动块的宽度.swiper-slide
设置完后效果是这样的:
在这里插入图片描述
需要给首尾两张分别添加左边距和右边距:

      .first-last-slide:first-of-type{
        margin-left: 38px;
      }
      .first-last-slide:last-of-type{
        margin-right: 38px;
      }
      .swiper-slide{
        width: 610px;
      } 

有一个需要注意的地方是,如果先new Swiper之后组件才获取到swiper里的数据,比如依赖接口或者props等,必须将下面两个参数设为true,否则会出现查看元素时所有滑动项都存在,但是页面上实际可滑动的只有第一张的情况:

  observer:true, 
  observeParents:true,
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现uniapp中swiper点击当前居中显示,可以使用swiper的change事件和uni.createSelectorQuery()方法,具体实现步骤如下: 1. 在swiper组件中加入change事件,代码如下: ``` <swiper @change="swiperChange"> // swiper的内容 </swiper> ``` 2. 在对应的vue组件中定义swiperChange方法,代码如下: ``` methods: { swiperChange(e) { const query = uni.createSelectorQuery().in(this); // 获取swiper-item的宽度 query.select('.swiper-item').boundingClientRect(data => { // 计算居中的位置 const center = (uni.getSystemInfoSync().windowWidth - data.width) / 2; // 计算当前的偏移量 const offset = e.detail.current * data.width; // 计算滑动的距离 const distance = center - offset; // 滑动swiper uni.createSelectorQuery().in(this.$refs.swiper).select('.uni-swiper__wrapper').fields({ size: true }, wrapperData => { this.$refs.swiper.swiperRef().scrollBy({ left: distance, top: 0, behavior: 'smooth' }); }).exec(); }).exec(); } } ``` 3. 在swiper-item中设置类名为swiper-item,以便在上述方法中获取该元素的宽度,代码如下: ``` <swiper-item class="swiper-item"> // swiper-item的内容 </swiper-item> ``` 4. 通过uni.createSelectorQuery()获取swiper-item的宽度,并根据当前的位置计算需要滑动的距离,调用swiper的scrollBy方法滑动到指定位置。 上述方法中,获取swiper-item宽度和计算居中位置的代码可以提取到mounted生命周期钩子中,避免重复计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值