最近有個需求是要新增一個左滑刪除的功能。參考了一下別的老哥的程式碼,做了一點點改進。記錄一下。以備不時之需
話不多說 ,上程式碼
<template>
<div class="slider-item">
<div
class="content"
@touchstart=`touchStart`
@touchmove=`touchMove`
@touchend=`touchEnd`
:style="deleteSlider"
>
<div class="remove">刪除</div>
</div>
</div>
</template>
<script>
// 獲取刪除按鈕的寬度,此寬度為滑塊左滑的最大距離
const DELBTNWIDTH = 60;
export default {
data() {
return {
startX: 0, // 開始pos
endX: 0, // 結束pos
moveX: 0, // 滑動時的pos
disX: 0, // 滑動距離
deleteSlider: `transform:translateX(0px)`,
};
},
methods: {
touchStart(timestamp, ev) {
ev = ev || event;
this.currSliderTimestamp = timestamp;
this.startX = 0;
// tounches類陣列,等於1時表示此時有隻有一隻手指在觸控螢幕
if (ev.touches.length === 1) {
// 記錄開始位置
this.startX = ev.touches[0].clientX;
console.log(this.startX, this.disX);
}
},
touchMove(timestamp, ev) {
ev = ev || event;
if (ev.touches.length === 1) {
// 滑動時距離瀏覽器左側實時距離
this.moveX = ev.touches[0].clientX;
//實時滑動距離,和上一次滑動做個銜接。防止第二次觸發的時候,位置不對的問題
this.disX = this.startX - this.moveX + this.disX;
// 如果是向右滑動或者不滑動,不改變滑塊的位置
if (this.disX > 0) {
if (this.disX < 100) {
this.deleteSlider = `transform:translateX(-` + this.disX + `px)`;
} else {
this.deleteSlider = `transform:translateX(-100px)`;
}
} else {
if (this.disX < -60) {
this.deleteSlider = `transform:translateX(60px)`;
} else {
this.deleteSlider = `transform:translateX(` + Math.abs(this.disX) + `px)`;
}
}
}
},
touchEnd() {
//滑動完成後,滑塊應該在的位置
if (this.disX < 100) {
this.deleteSlider = `transform:translateX(0px)`;
this.disX = 0;
} else {
this.deleteSlider = `transform:translateX(-` + DELBTNWIDTH + `px)`;
this.disX = 60;
}
},
},
};
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
.slider-item {
width: 100%;
height: 60px;
border-bottom: 1px solid #eeeeee;
overflow: hidden;
display: flex;
position: relative;
.content {
min-width: 100%;
height: 100%;
background: yellow;
box-sizing: normal-box;
padding-right: 60px;
position: relative;
transition-property: all;
transition-duration: 0.4s;
transition-timing-function: cubic-bezier(0, 0.85, 0.72, 0.86);
transition-delay: 0s;
.remove {
position: absolute;
top: 0;
right: 0;
width: 60px;
height: 60px;
background: #fe5ba8;
text-align: center;
line-height: 60px;
font-size: 15px;
color: #ffffff;
}
}
}
</style>