一起创业网-为互联网创业者服务

小程序怎么写滑动删除

在微信小程序中实现滑动删除功能,通常需要以下几个步骤:

布局:

在`wxml`中定义列表项的布局,并为每个列表项绑定`touchstart`和`touchmove`事件。

事件处理:

在`js`中处理滑动事件,判断滑动是否有效,并更新数据源。

样式:

通过`wxss`设置列表项的样式,使其在滑动时产生动画效果。

1. 布局

在`wxml`中定义列表项的布局,并为每个列表项绑定`touchstart`和`touchmove`事件:

```xml

data-index="{{index}}"

bindtouchstart="onTouchStart"

bindtouchmove="onTouchMove"

bindtouchend="onTouchEnd"

>

{{item.name}}

```

2. 事件处理

在`js`中处理滑动事件:

```javascript

Page({

data: {

items: [

{ id: 1, name: 'Item 1' },

{ id: 2, name: 'Item 2' },

{ id: 3, name: 'Item 3' },

// 其他列表项

],

startX: 0,

startY: 0,

currentIndex: -1,

isDragging: false

},

onTouchStart(e) {

const { index } = e.currentTarget.dataset;

this.setData({

startX: e.touches.clientX,

startY: e.touches.clientY,

currentIndex: index,

isDragging: true

});

},

onTouchMove(e) {

if (!this.data.isDragging) return;

const { startX, startY, currentIndex } = this.data;

const touchX = e.touches.clientX;

const touchY = e.touches.clientY;

const deltaX = touchX - startX;

// 判断是否滑动超过30度角

const angle = Math.atan2(touchY - startY, touchX - startX) * (180 / Math.PI);

if (Math.abs(angle) > 30) return;

// 滑动到当前索引

if (deltaX > 0 && currentIndex === this.data.items.length - 1) return;

if (deltaX < 0 && currentIndex === 0) return;

// 更新数据源

const newItems = this.data.items.slice();

newItems[currentIndex] = { ...newItems[currentIndex], isDragging: true };

this.setData({ items: newItems });

},

onTouchEnd(e) {

if (!this.data.isDragging) return;

const { currentIndex } = this.data;

const { startX } = this.data;

const touchX = e.changedTouches.clientX;

const deltaX = touchX - startX;

// 判断是否滑动超过阈值

const threshold = 50; // 可以根据需要调整

if (Math.abs(deltaX) > threshold) {

// 删除当前索引的项

const newItems = this.data.items.filter((_, i) => i !== currentIndex);

this.setData({ items: newItems });

} else {

// 恢复原始位置

this.setData({

items: this.data.items.map((_, i) => (i === currentIndex ? { ...this.data.items[currentIndex], isDragging: false } : item)),

isDragging: false

});

}

}

});

```

3. 样式

在`wxss`中设置列表项的样式: