微信小程序列表中item左滑删除功能

时间:2021-05-18

第一步:把想要的两种样式写出来

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左滑删除功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章