Vue3可以直接使用,其余也只需略微修改
HTML
<template>
<div class="slider">
<div class="listItem" ref="dom" @mousedown.capture="touchStart" @mouseup.capture="touchEnd" @touchstart.capture="touchStart" @touchend.capture="touchEnd">
<div class="slotArea" @mouseup.stop="emit('itemClick')" @touchend.stop="emit('itemClick')">
<slot></slot>
</div>
<div class="btns">
<!-- <div class="btn" @mouseup="emit('itemClick')" @touchend="emit('remote')">远程协助</div>-->
<div class="btn" @mouseup.stop="emit('del')" @touchend.stop="emit('del')" style="background: red">刪除</div>
</div>
</div>
</div>
</template>
JS
<script setup>
import { ref } from 'vue';
const emit = defineEmits(['itemClick','remote','del']);
const startX = ref(0);
const endX = ref(0);
const dom = ref(null);
// 滑动开始
const touchStart = (e)=> {
e.stopPropagation();
// 判断是否为触摸操作
startX.value =e.touches? e.touches[0].clientX:e.x;
}
const touchEnd=(e)=> {
// 判断是否为触摸操作
endX.value =e.changedTouches? e.changedTouches[0].clientX:e.x;
if (startX.value - endX.value > 50) {
// 需要获取dom,但不能用e.target,因为抬起的时候可能在按钮上
dom.value.classList.add('act');
e.stopPropagation();
e.preventDefault();
}
// 按需调节灵敏度
if (startX.value - endX.value < -30) {
dom.value.classList.remove('act');
e.stopPropagation();
e.preventDefault();
}
// 复位
startX.value = 0;
endX.value = 0;
}
</script>
CSS
<style scoped>
.slider {
background-color: #ffffff;
overflow: hidden;
width: 100%;
}
.listItem{
user-select: none;
width: 100%;
position: relative;
display: flex;
-webkit-transition: all 0.2s;
transition: all 0.2s;
transform:translate3d(0, 0, 0) ;
}
.listItem.act{
transform: translate3d(-119px, 0, 0);
}
.slotArea{
width: 100%;
flex-shrink: 0;
}
.btns{
width: 119px;
display: flex;
justify-content: center;
align-items: center;
color: #ffffff;
font-size: .3611rem;
}
.btns .btn{
width: 119px;
height: 79px;
display: flex;
justify-content: center;
align-items: center;
line-height: 20px;
background-color: rgba(21,143,253,1);
color: rgba(255,255,255,1);
font-size: 14px;
cursor: pointer;
}
</style>