微信小程序左滑刪除效果的實現,平時用到的app也有使用到這種效果,對組件向左滑動,右側會出現一個刪除按鈕,點擊確認刪除此組件模塊;
效果圖如下:
wxml:
<view class="collect">
<view class="touch-item {{item.isTouchMove ? 'touch-move-active' : ''}}" data-index="{{index}}"
bindtouchstart="touchstart" bindtouchmove="touchmove" wx:for="{{items}}" wx:key="">
<view class="content">
<view class='com'>
<view class='tp'>
<image src="{{item.img}}" class='img' />
</view>
<view class='txt'>
<view class='tit'>{{item.title}}</view>
<view class='bot'>
<view class="pri {{item.type==0? 'pri-buy':'pri-play'}}"><label class='num'>¥{{item.price}}</label></view>
<navigator class='a' wx:if = "{{item.type==0}}">
<image src="../imgs/ico-buy.png" class='ico' />
<label class='ti'>購買</label>
</navigator>
<navigator class='a' wx:else>
<image src="../imgs/ico-play.png" class='ico' />
<label class='ti'>播放</label>
</navigator>
</view>
</view>
</view>
</view>
<view class="del" catchtap="cancleCollect" data-index="{{index}}">取消收藏</view>
</view>
</view>
js代碼:
//開始觸摸時
touchstart(e) {
var that = this;
that.data.items.forEach(function (v, i) {
if (v.isTouchMove){
v.isTouchMove = false;
}
})
that.setData({
startX: e.changedTouches[0].clientX,
startY: e.changedTouches[0].clientY,
items: that.data.items
})
},
//滑動事件處理
touchmove(e) {
var that = this,
index = e.currentTarget.dataset.index,
startX = that.data.startX,//開始X座標
startY = that.data.startY,//開始Y座標
touchMoveX = e.changedTouches[0].clientX,//滑動變化座標
touchMoveY = e.changedTouches[0].clientY,//滑動變化座標
//獲取滑動角度
angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
that.data.items.forEach(function (v, i) {
v.isTouchMove = false
//滑動超過30度角 return
if (Math.abs(angle) > 30) return;
if (i == index) {
if (touchMoveX > startX){
v.isTouchMove = false; //右滑
}else{
v.isTouchMove = true; //左滑
}
}
})
that.setData({
items: that.data.items
})
},
// 計算滑動角度 start 起點座標 end 終點座標
angle(start, end) {
var _X = end.X - start.X,
_Y = end.Y - start.Y
//返回角度 /Math.atan()返回數字的反正切值
return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
},
//取消收藏
cancleCollect(e) {
var that = this,
index = e.currentTarget.dataset.index,
items = that.data.items;
items[index].isTouchMove = true;
that.setData({
items: items
})
wx.showModal({
title: '溫馨提示',
content: '親,您確定要取消此收藏嗎?',
success(res) {
if (res.confirm) {
items.splice(index, 1);
that.setData({
items: items
})
wx.showToast({
title: '取消收藏成功~',
icon: 'success',
duration: 1500
})
} else if (res.cancel) {
items[index].isTouchMove = false;
that.setData({
items: items
})
}
}
})
},
如發現什麼問題提可以留言交流哦,謝謝~
具體案列可訪問:https://github.com/xiexikang/xcx-left-sliding-delete