您好,小程序模板欢迎您。
小程序模板
当前位置 : 首页> 小程序教程> 微信小程序实现左右滑动进行切换数据页面(touchmove)

微信小程序实现左右滑动进行切换数据页面(touchmove)

下面是微信小程序实现左右滑动进行切换数据页面的代码示例:


1. 在 wxml 文件中,创建一个 swiper 组件:


  {{item}}


2. 在 js 文件中,定义 swiper 组件的滑动事件:

Page({
  data: {
    current: 0,
    startX: 0, // 开始触摸的位置
    startY: 0, // 开始触摸的位置
    moveX: 0, // 移动时的位置
    moveY: 0, // 移动时的位置
    list: ['第一页', '第二页', '第三页'], // 数据列表
  },

  // swiper 组件滑动事件
  swiperChange: function (e) {
    this.setData({
      current: e.detail.current
    })
  },

  // swiper 组件触摸移动事件
  swiperTouchMove: function (e) {
    let startX = this.data.startX;
    let startY = this.data.startY;
    let moveX = e.changedTouches[0].clientX;
    let moveY = e.changedTouches[0].clientY;
    let X = moveX - startX;
    let Y = moveY - startY;

    // 判断是否为左右滑动
    if (Math.abs(X) > Math.abs(Y)) {
      if (X < 0) { // 左滑
        this.setData({
          current: this.data.current + 1
        })
      } else { // 右滑
        this.setData({
          current: this.data.current - 1
        })
      }
    }
  },

  // swiper 组件触摸开始事件
  swiperTouchStart: function (e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY
    })
  },
})


3. 在 wxss 文件中,设置 swiper 组件的样式:

.swiper {
  height: 100%;
}

.swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}

这样就可以实现在微信小程序中左右滑动进行切换数据页面了。

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了