下面是微信小程序实现左右滑动进行切换数据页面的代码示例:
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;
}这样就可以实现在微信小程序中左右滑动进行切换数据页面了。
上一篇:微信小程序蓝牙自动连接功能
下一篇:setData性能问题如何优化