小程序左滑动删除功能

 <view data-index='{{index}}' bindtouchstart="touchS" bindtouchmove="touchM" bindtouchend="touchE" data-index="{{index}}" class="inner txt" style="{{item.txtStyle}}"></view>

========================= 将上面标签套在需要有左滑删除功能的标签上==================
delBtnWidth: 80, //声明的变量

touchS: function(e) {
if (e.touches.length == 1) {
this.setData({
//设置触摸起始点水平方向位置
startX: e.touches[0].clientX
});
}
},

touchM: function(e) {
if (e.touches.length == 1) {
//手指移动时水平方向位置
var moveX = e.touches[0].clientX;
//手指起始点位置与移动期间的差值
var disX = this.data.startX - moveX;
var delBtnWidth = this.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”;
}
}
//获取手指触摸的是哪一项
var index = e.currentTarget.dataset.index;
var Details = this.data.Details;
if (index >= 0) {
Details[index].txtStyle = txtStyle;
//更新列表的状态
this.setData({
Details: Details
});
}
}
},

touchE: function(e) {
if (e.changedTouches.length == 1) {
//手指移动结束后水平位置
var endX = e.changedTouches[0].clientX;
//触摸开始与结束,手指移动的距离
var disX = this.data.startX - endX;
var delBtnWidth = this.data.delBtnWidth;
//如果距离小于删除按钮的1/2,不显示删除按钮
var txtStyle = disX > delBtnWidth / 2 ? “left:-” + delBtnWidth + “px” : “left:0px”;
//获取手指触摸的是哪一项
var index = e.currentTarget.dataset.index;
var Details = this.data.Details;
if (index >= 0) {
Details[index].txtStyle = txtStyle;
Details.forEach((e, k) => {
if (k != index) {
e.txtStyle = ‘left:0px’;
}
})
//更新列表的状态
this.setData({
Details: Details
});
}
}
},
//获取元素自适应后的实际宽度
getEleWidth: function(w) {
var real = 0;
try {
var res = wx.getSystemInfoSync().windowWidth;
var scale = (750 / 2) / (w / 2);
//以宽度750px设计稿做宽度的自适应
real = Math.floor(res / scale);
return real;
} catch (e) {
return false;
// Do something when catch error
}
},
initEleWidth: function() {
var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
this.setData({
delBtnWidth: delBtnWidth
});
},
=上面是JS部分===============
.inner {
position: absolute;
top: 0;
}

.inner.txt {
background-color: #fff;
height: 38px;
width: 100%;
z-index: 5;
padding-right: 80px;
transition: left 0.2s ease-in-out;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

.inner.del {
background-color: #e64340;
line-height: 38px;
width: 80px;
text-align: center;
z-index: 4;
right: 0;
color: #fff;
box-sizing: border-box;
}
=样式部分根据需要调整宽高===
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值