第一步:把想要的兩種樣式寫出來
1.正常顯示的樣式
css:
.box{ height: 100%; } .item{ position:relative; top: 0; width: 100%; height: 150rpx; border-bottom: #d9d9d9 solid 1rpx; padding: 0; } .item .content{ background-color: #ffffff; height: 100%; position: relative; left: 0; width: 100%; transition: all 0.3s; } .item .del-button { position: absolute; right: -140rpx; width: 140rpx; height: 100%; background-color: #df3448; color: #fff; top: 0; text-align: center; display: flex; justify-content: center; align-items: center; transition: all 0.3s; font-size: 24rpx; }
xwml:
<view class="box"> <view class="item {{status ? '' :'active'}}"> <view class="content">顯示正常內容</view> <view class="del-button">刪除</view> </view> </view>
2.顯示刪除按鈕
.item.active .content{ left: -140rpx; } .item.active .del-button{ right: 0; }
同時在js中控制樣式是否active
data: { status:false //true為正常顯示,false為顯示刪除按鈕 },
第二步:綁定事件
其實此時可以綁定bindtap事件,來切換active的狀態,點擊一下是“顯示正常內容”,再點擊一下是“刪除”。然后,現在把點擊事件改成touch并向左move之后再觸發,就很好理解了。(樣式中,已經提前寫好的transition: all 0.3s;就是為了使兩個狀態之間有個過渡)
微信小程序提供了兩個事件可以使用,一個是bindtouchstart,通過這個事件我們可以獲得用戶剛點擊(手指還未抬起)時的坐標。
touchS(e) { // 獲得起始坐標 this.startX = e.touches[0].clientX; this.startY = e.touches[0].clientY; },
還有一個是bindtouchmove,我們可以一直獲取當前的坐標(用戶手指一直在屏幕上滑動時)。因此,我們只需要得到x軸上的移動的前后坐標相減是正數,就是向左移動。
touchM(e) { // 獲得當前坐標 this.currentX = e.touches[0].clientX; this.currentY = e.touches[0].clientY; const x = this.startX - this.currentX; //橫向移動距離 const y = Math.abs(this.startY - this.currentY); //縱向移動距離,若向左移動有點傾斜也可以接受 if (x > 35 && y < 110) { //向左滑是顯示刪除 this.setData({ status: false }) } else if (x < -35 && y < 110) { //向右滑 this.setData({ status: true }) } },
然后綁定到Item上
<view class="box"> <view class="item {{status ? '' :'active'}}"> <view class="content" bindtouchstart="touchS" bindtouchmove="touchM">顯示正常內容</view> <view class="del-button">刪除</view> </view> </view>
最后再在刪除的view里bindtap一個刪除方法即可刪除。
以上是最簡版的效果,還需很多優化要自行添加。
總結
以上所述是小編給大家介紹的微信小程序列表中item左滑刪除功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com