实现列表组件的侧滑删除(Swipe to Delete),核心思路是:在列表每一项中放一个“内容层”和一个“操作层(删除按钮)”,通过手势或鼠标拖拽让内容层向左滑动,露出删除按钮,点击后删除该项。
下面分 Web(前端) 和 移动端(Flutter / React Native) 常见实现方式说明。
<ul class="list">
<li class="item">
<div class="content">列表项内容</div>
<button class="delete">删除</button>
</li>
</ul>
.item {
position: relative;
overflow: hidden;
height: 50px;
}
.content {
position: absolute;
width: 100%;
height: 100%;
background: #fff;
transition: transform 0.3s;
}
.delete {
position: absolute;
right: 0;
width: 80px;
height: 100%;
background: red;
color: #fff;
border: none;
}
let startX = 0;
let currentX = 0;
document.querySelectorAll('.item').forEach(item => {
const content = item.querySelector('.content');
item.addEventListener('touchstart', e => {
startX = e.touches[0].clientX;
});
item.addEventListener('touchmove', e => {
currentX = e.touches[0].clientX - startX;
if (currentX < 0) {
content.style.transform = `translateX(${currentX}px)`;
}
});
item.addEventListener('touchend', () => {
if (currentX < -40) {
content.style.transform = 'translateX(-80px)';
} else {
content.style.transform = 'translateX(0)';
}
});
item.querySelector('.delete').onclick = () => {
item.remove();
};
});
v-for 渲染列表@touchstart、@touchmove 控制 style.transformlist.splice(index, 1)state 保存 offsetonTouchMove 更新 offsetsetList(list.filter(...))Flutter 自带 Dismissible:
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Dismissible(
key: Key(items[index]),
onDismissed: (direction) {
setState(() {
items.removeAt(index);
});
},
background: Container(color: Colors.red),
child: ListTile(title: Text(items[index])),
);
},
);
使用 react-native-swipe-list-view:
<SwipeListView
data={data}
renderItem={rowData => <Text>{rowData.item.title}</Text>}
renderHiddenItem={rowData => (
<TouchableOpacity onPress={() => deleteItem(rowData.item.id)}>
<Text>删除</Text>
</TouchableOpacity>
)}
leftOpenValue={0}
rightOpenValue={-75}
/>
transform 提升性能如果你说明具体技术栈(Vue / React / 小程序 / Flutter),我可以给你完整可直接用的代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。