今天我們說下微信小程序左滑刪除效果的實現,現在市場上很多APP都在使用這個效果,一個listView頁面,向左滑動一條item時,右側會出現一個刪除或者其他的選項,用戶體驗非常好,操作起來十分方便,今天我們使用微信小程序來實現這個效果.......
先看效果
要實現的效果
要實現的效果:
1,當向左滑動時,item跟隨手指像左移動,同時右側出現兩個可點擊的按鈕
2,當滑動距離大于按鈕寬度一半松開手指時,item自動滑動到左側顯示出按鈕,小于一半時item自動回到原來的位置,隱藏按鈕。
思路:
1,首先頁面每個item分為上下兩層,上面一層放置正常內容,下面一層放置左滑顯示出的按鈕,這個可以使用z-index來實現分層。
2,item上層使用絕對定位,我們操縱 left 屬性的值來實現像左移動。
3,我們通過微信小程序api提供的touch對象和3個有關手指觸摸的函數(touchstart,touchmove,touchend)來實現item隨手指移動。
小程序api-touch對象
Paste_Image.png
由于比較簡單,所以直接上代碼了,詳細的講解都在代碼的注釋中,首先看下頁面的布局
<!--這是一個item的代碼>
<view class="address-item" wx:for="{{addressList}}" >
<!--這里綁定了剛才說的3個函數分別為 touchS,touchM touchE-->
<!--這里注意這個 style="{{item.txtStyle}}" ,這是我們一會再js中 將要設置的樣式 -->
<view style="{{item.txtStyle}}" bindtouchstart="touchS" bindtouchmove="touchM" bindtouchend="touchE" data-index="{{index}}" class="address-item-top" >
<!--中間無關的代碼已被我刪除-->
</view>
<!--這里是左滑按鈕部分----start-->
<view bindtap="delItem" class="posit">
<view class="editor" data-addressid="{{item.address.ID}}" catchtap="setDefaultAddress">設為默認地址</view>
<view class="del" data-addressid="{{item.address.ID}}" data-index="{{index}}" catchtap="delAddress">刪除</view>
</view>
<!--這里是左滑按鈕部分----end-->
</view>
再看js代碼
Page({
data:{
addressList:[{"Contact":"鐘誠","Mobile":13888888888,"Address":"江蘇省蘇州市工業園區創意產業園"},
{"Contact":"凹凸曼","Mobile":13666666666,"Address":"江蘇省蘇州市工業園區獨墅湖體育館"},
{"Contact":"圖傲曼","Mobile":13666666666,"Address":"江蘇省蘇州市工業園區獨墅湖體育館"}],
editIndex:0,
delBtnWidth:150//刪除按鈕寬度單位(rpx)
},
onLoad:function(options){},
//手指剛放到屏幕觸發
touchS:function(e){
console.log("touchS"+e);
//判斷是否只有一個觸摸點
if(e.touches.length==1){
this.setData({
//記錄觸摸起始位置的X坐標
startX:e.touches[0].clientX
});
}
},
//觸摸時觸發,手指在屏幕上每移動一次,觸發一次
touchM:function(e){
console.log("touchM:"+e);
var that = this
if(e.touches.length==1){
//記錄觸摸點位置的X坐標
var moveX = e.touches[0].clientX;
//計算手指起始點的X坐標與當前觸摸點的X坐標的差值
var disX = that.data.startX - moveX;
//delBtnWidth 為右側按鈕區域的寬度
var delBtnWidth = that.data.delBtnWidth;
var txtStyle = "";
if(disX == 0 || disX < 0){//如果移動距離小于等于0,文本層位置不變
txtStyle = "left:0px";
}else if(disX > 0 ){//移動距離大于0,文本層left值等于手指移動距離
txtStyle = "left:-"+disX+"px";
if(disX>=delBtnWidth){
//控制手指移動距離最大值為刪除按鈕的寬度
txtStyle = "left:-"+delBtnWidth+"px";
}
}
//獲取手指觸摸的是哪一個item
var index = e.currentTarget.dataset.index;
var list = that.data.addressList;
//將拼接好的樣式設置到當前item中
list[index].txtStyle = txtStyle;
//更新列表的狀態
this.setData({
addressList:list
});
}
},
touchE:function(e){
console.log("touchE"+e);
var that = this
if(e.changedTouches.length==1){
//手指移動結束后觸摸點位置的X坐標
var endX = e.changedTouches[0].clientX;
//觸摸開始與結束,手指移動的距離
var disX = that.data.startX - endX;
var delBtnWidth = that.data.delBtnWidth;
//如果距離小于刪除按鈕的1/2,不顯示刪除按鈕
var txtStyle = disX > delBtnWidth/2 ? "left:-"+delBtnWidth+"px":"left:0px";
//獲取手指觸摸的是哪一項
var index = e.currentTarget.dataset.index;
var list = that.data.addressList;
list[index].txtStyle = txtStyle;
//更新列表的狀態
that.setData({
addressList:list
});
}
}
結束!不足請指教