touchend中处理最终效果,如果滑动距离不大于某一值则恢复原位,否则切换。
touchEnd() {
console.log("end");
console.log(this.percent);
let offsetWidth
let percent
//当前为红色,滑动占比大于0.1则切换,否则回到原位置
if(this.currentPlay === 'red'){
if(this.percent > 0.1) {
this.currentPlay = 'yellow'
offsetWidth = -window.innerWidth
} else {
offsetWidth = 0
}
} else {
//当前为黄色,滑动占比大于0.9则切换,否则回到原位置
if(this.percent < 0.9) {
this.currentPlay = 'red'
offsetWidth = 0
} else {
offsetWidth = -window.innerWidth
}
}
//这里的transform是针对最开始的位置而言,而不是移动过程中的位置
this.$refs.back.style["transform"] = `translate3d(${offsetWidth}px,0,0)`
this.$refs.back.style["transitionDuration"] = 10
}完整代码
<template lang="html">
<div class="back"
@touchstart.prevent="touchStart" @touchmove.prevent="touchMove"
@touchend="touchEnd" ref="back">
<div class="back-l" ref="left"></div>
<div class="back-r" ref="right"></div> </div>
</template>
<script>
export default {
data() {
return {
currentPlay: 'red',
percent: 0
}
},
created() {
this.touch = {}
},
methods: {
touchStart(e) {
const touch = e.touches[0] this.touch.startX = touch.pageX
this.touch.startY = touch.pageY
},
touchMove(e) {
console.log("move");
const touch = e.touches[0] const deltaX = touch.pageX - this.touch.startX
const deltaY = touch.pageY - this.touch.startY
if (Math.abs(deltaY) > Math.abs(deltaX)) {
return
}
const left = this.currentPlay == 'red' ? 0 : -window.innerWidth
var offsetWidth = Math.min(0, Math.max(-window.innerWidth,left+deltaX))
this.percent = Math.abs(offsetWidth/window.innerWidth)
this.$refs.back.style["transform"] = `translate3d(${offsetWidth}px,0,0)`
this.$refs.back.style["transitionDuration"] = 10
},
touchEnd() {
console.log("end");
console.log(this.percent);
let offsetWidth
let percent
if(this.currentPlay === 'red'){
if(this.percent > 0.1) {
this.currentPlay = 'yellow'
offsetWidth = -window.innerWidth
} else {
offsetWidth = 0
}
} else {
if(this.percent < 0.9) {
this.currentPlay = 'red'
offsetWidth = 0
} else {
offsetWidth = -window.innerWidth
}
}
this.$refs.back.style["transform"] = `translate3d(${offsetWidth}px,0,0)`
this.$refs.back.style["transitionDuration"] = 10










