小程序 右滑删除按钮怎么做
时间: 2023-07-19 07:13:04 浏览: 32
在小程序中实现右滑删除按钮,一般可以使用 `swiper` 组件来实现。具体实现步骤如下:
1. 在列表项中添加 `swiper-item` 组件,用于包裹右滑删除按钮。
2. 在 `swiper-item` 组件中添加一个 `view` 组件,用于显示删除按钮,并设置该组件的样式为向左浮动。
3. 在 `swiper` 组件上添加 `bindchange` 事件,用于监听滑动事件。
4. 在 `bindchange` 事件中获取当前滑动的 `swiper-item` 组件的 `current` 值,通过 `setData` 方法更新 `swiper-item` 组件的样式,使其向左浮动显示删除按钮。
下面是一个示例代码,供参考:
```
<!-- 列表项 -->
<view class="list-item">
<!-- swiper 组件 -->
<swiper class="swiper" bindchange="onSwiperChange" data-index="{{index}}">
<!-- swiper-item 组件 -->
<swiper-item>
<!-- 删除按钮 -->
<view class="delete-btn" bindtap="onDelete">删除</view>
</swiper-item>
</swiper>
<!-- 列表内容 -->
<view class="content">{{item.content}}</view>
</view>
```
```
// 页面逻辑
Page({
data: {
list: [
{ content: '列表项1' },
{ content: '列表项2' },
{ content: '列表项3' }
]
},
// swiper 组件变化事件
onSwiperChange: function(e) {
let index = e.currentTarget.dataset.index;
let current = e.detail.current;
if (current === 1) {
// 如果当前滑动到了第二个 swiper-item,更新列表项样式
let key = `list[${index}].swiperClass`;
this.setData({
[key]: 'swiper-left'
});
}
},
// 删除按钮点击事件
onDelete: function(e) {
let index = e.currentTarget.dataset.index;
// 在数据中删除列表项
let list = this.data.list;
list.splice(index, 1);
// 更新数据
this.setData({
list: list
});
}
})
```
```
/* 样式文件 */
.list-item {
position: relative;
height: 50px;
line-height: 50px;
border-bottom: 1px solid #eee;
}
.swiper {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 120rpx;
}
.swiper-item {
height: 50px;
}
.delete-btn {
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 60rpx;
background-color: red;
color: #fff;
text-align: center;
line-height: 50px;
}
.swiper-left {
transform: translateX(-60rpx);
}
```