微信小程序左滑动
在微信小程序中,实现左滑动功能可以通过监听touchstart
、touchmove
和touchend
事件来实现。以下是一个简单的示例:
- 在
wxml
文件中,添加一个可滑动的视图:
<view class="scroll-view" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd">
<view wx:for="{{items}}" wx:key="index" style="height: 100rpx; background-color: {{item.color}};"></view>
</view>
- 在
wxss
文件中,设置可滑动视图的样式:
.scroll-view {
height: 100vh;
overflow-x: hidden;
}
- 在
js
文件中,实现触摸事件的回调函数:
Page({
data: {
items: [
{ color: 'red' },
{ color: 'green' },
{ color: 'blue' },
{ color: 'yellow' },
{ color: 'purple' },
],
},
touchStart(e) {
this.startX = e.touches[0].clientX;
this.startY = e.touches[0].clientY;
},
touchMove(e) {
const moveX = e.touches[0].clientX;
const moveY = e.touches[0].clientY;
const deltaX = moveX - this.startX;
const deltaY = moveY - this.startY;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
// 水平滑动
if (deltaX > 0) {
// 向左滑动
console.log('向左滑动');
} else {
// 向右滑动
console.log('向右滑动');
}
} else {
// 垂直滑动
console.log('垂直滑动');
}
},
touchEnd() {
console.log('触摸结束');
},
});
在这个示例中,我们创建了一个可水平滚动的scroll-view
视图,并在触摸事件回调函数中计算滑动的方向。当用户向左或向右滑动时,控制台将输出相应的提示信息。