小程序swiper带切换按钮

本文介绍了小程序中Swiper组件的使用,包括设置同时显示的滑块数量、切换动画时间、监听滑动事件以及实现循环滑动等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小程序自带swiper组件,

display-multiple-items 同时显示的滑块数量
current: 当前所在滑块的 index
duration:切换需要花的时间 一般为1秒
bindchange:current发生改变触发
bindanimationfinish:动画结束时触发
circular 是否采用衔接滑动

      <view class="swiperCont">
        <view class="activeBtn1" bindtap="toLeft"></view>
        <view class="activeBtn2" bindtap="toRight"></view>

        <swiper current="{
    
    {currentIndex}}" circular="true" duration="1000" bindchange="changeIndex" bindanimationfinish="changeFinish" display-multiple-items="4">
          <swiper-item wx:for="{
    
    {[1, 2, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]}}" wx:key="index" bindtap="openPop" data-type="choose" data-ind="index">
            <view 
### 微信小程序中通过按钮控制 Swiper 切换微信小程序中,可以通过绑定事件的方式让按钮控制 `swiper` 的行为。具体来说,可以利用 `wx.createSelectorQuery()` 方法获取到 `swiper` 实例,并调用其方法(如 `.setCurrentItem(index)`)来改变当前展示的内容。 以下是实现该功能的一个完整示例: #### WXML 文件 ```xml <view class="container"> <!-- 按钮组 --> <button bindtap="prevSlide">上一张</button> <button bindtap="nextSlide">下一张</button> <!-- Swiper 容器 --> <swiper id="mySwiper" circular="{{true}}" duration="500"> <swiper-item> <image src="/images/1.jpg"></image> </swiper-item> <swiper-item> <image src="/images/2.jpg"></image> </swiper-item> <swiper-item> <image src="/images/3.jpg"></image> </swiper-item> </swiper> </view> ``` #### WXSS 文件 ```css /* 基本样式 */ .container { display: flex; flex-direction: column; align-items: center; } button { margin: 10px; } ``` #### JS 文件 ```javascript Page({ data: { currentIndex: 0, // 当前索引 }, prevSlide() { const current = this.data.currentIndex; let newIndex = current === 0 ? 2 : current - 1; // 如果已经是第一页,则跳到最后一页 this.setData({ currentIndex: newIndex }); this.changeSwiper(newIndex); }, nextSlide() { const current = this.data.currentIndex; let newIndex = current === 2 ? 0 : current + 1; // 如果已经最后一页,则跳回第一页 this.setData({ currentIndex: newIndex }); this.changeSwiper(newIndex); }, changeSwiper(index) { const query = wx.createSelectorQuery(); query.select('#mySwiper').fields({ size: true, scrollOffset: true }, res => { if (res) { const swiperInstance = wx.createAnimation(); // 获取动画实例 res.swiper.scrollTo(index); // 设置滚动位置 } }).exec(); // 或者直接使用 setCurrentItem 方法 wx.createSelectorQuery().select('#mySwiper').node(res => { if (res && res.node) { res.node.dataset.current = index.toString(); res.node.setCurrentItem(index); } }).exec(); }, }); ``` 上述代码实现了两个按钮分别控制 `swiper` 向左和向右切换的功能[^1]。其中,`.setCurrentItem(index)` 是核心方法,用于指定要显示的 `swiper-item` 索引[^2]。 --- ### 注意事项 - 需要在页面加载完成后初始化 `swiper` 数据。 - 使用 `circular=true` 属性可以让轮播具有循环效果。 - 图片路径 `/images/*.jpg` 应替换为实际项目中的资源路径。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值