左滑删除在移动端很常见。下面我们一起来封装一下这个简单的小组件。我们想要是:
- 当滑块没有超过删除按钮的一半时自动回到起点位置。
- 滑动距离超过一半滑动到最大值(删除按钮宽度)
- 尽量精简代码
效果如下:
在开始之前,我们先得将 [touchEventApi][1]弄清楚了。这个小组件中,用到了:
1. TouchEvent.touches (表示一 个 TouchList 对象,包含了所有当前接触触摸平面的触点的Touch对象)
2. TouchEvent.changedTouches (一个 TouchList 对象,包含了代表所有从上一次触摸事件到此次事件过程中,
状态发生了改变的触点的 Touch 对象。)
话不多说,直接上代码:
删除
然后是css,这里我使用的是less
.slider{ width: 100%; height:200px; position: relative; user-select: none; .content{ position: absolute; left: 0; right: 0; top: 0; bottom: 0; background:green; z-index: 100; // 设置过渡动画 transition: 0.3s; } .remove{ position: absolute; width:200px; height:200px; background:red; right: 0; top: 0; color:#fff; text-align: center; font-size: 40px; line-height: 200px; } }
到这里就全部完成了,希望对大家有帮助!也希望大家多多支持考高分网。



