在使用wepy框架中,对左滑删除功能做解释,通过touch事件的起止,完成事件的绑定和数据刷新,来达到效果,大致代码如下:
wxml
<view class="touch-item" @touchstart="touchS" @touchmove="touchM" @touchend="touchE" data-index="{{idx}}" style="{{value.position}}" data-channel="{{index}}"></view>
script中
//滑动删除操作
touchS(e) {
if(e.touches.length==1){
//设置触摸起始点水平方向位置
this.startX = e.touches[0].clientX
}
}
touchM(e) {
if(e.touches.length==1){
//手指移动时水平方向位置
let moveX = e.touches[0].clientX
//手指起始点位置与移动期间的差值
let disX = this.startX - moveX
let delBtnWidth = this.delBtnWidth
let position = ""
if(disX == 0 || disX < 0){//如果移动距离小于等于0,文本层位置不变
position = "margin-left: 0rpx"
}else if(disX > 0 ){//移动距离大于0,文本层margin-left值等于手指移动距离
position = "margin-left:-"+disX+"rpx"
if(disX>=delBtnWidth){
//控制手指移动距离最大值为删除按钮的宽度
position = "margin-left:-"+delBtnWidth+"rpx"
}
}
//获取手指触摸的是哪一项
let index = e.currentTarget.dataset.index
//判断频道
let channel = e.currentTarget.dataset.channel
if(index >= 0){
//根据数据类型更新状态
this.cartInfo[channel].shopcartList[index].position = position
this.$apply()
}
}
}
//用于滑动距离不够时,恢复原来状态
touchE(e) {
if(e.changedTouches.length==1){
//手指移动结束后水平位置
let endX = e.changedTouches[0].clientX
//触摸开始与结束,手指移动的距离
let disX = this.startX - endX
let delBtnWidth = this.delBtnWidth
//如果距离小于删除按钮的1/3,不显示删除按钮
let position = disX > delBtnWidth/3 ? "margin-left:-"+delBtnWidth+"rpx":"margin-left:0rpx"
//获取手指触摸的是哪一项
let index = e.currentTarget.dataset.index
//判断频道
let channel = e.currentTarget.dataset.channel
if(index >= 0){
//更新状态
this.cartInfo[channel].shopcartList[index].position = position
this.$apply()
}
}
}
引入即实现。完。