touch事件
<template>
<div
class="scrollview"
@touchstart="touchstart"
@touchmove="touchmove"
@touchend="touchend"
@touchcancel="touchcancel"
>
<div class="container" ref="container" :class="{ani:isAni}" :style="containerLeft">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {
// 记录上一个触摸事件的x坐标
lastPointX: 0,
// 当前容器container的横坐标偏移量
x: 0,
// 是否有动画
isAni: false
};
},
computed: {
containerLeft() {
return {
left: this.x + "px"
};
}
},
methods: {
touchstart(e) {
this.isAni = false;
// console.log("touchstart:手指触摸屏幕的一瞬间触发");
// e.touches:是一个列表,表示当前屏幕的触摸点(有几个手指摁到屏幕上了)
// e.touches[0].pageX:当前触摸点距离屏幕左边的距离
this.lastPointX = e.touches[0].pageX;
},
touchmove(e) {
this.isAni = false;
// console.log("touchmove:手指在屏幕上触摸移动时触发");
var nowPointX = e.touches[0].pageX;
var offset = nowPointX - this.lastPointX;
// 判断边界问题
if (
this.x >= 0 ||
this.x <= this.$el.clientWidth - this.$refs.container.clientWidth
) {
this.x = this.x + offset / 2;
} else {
this.x = this.x + offset;
}
this.isAni = true;
// 重置lastPointX
this.lastPointX = nowPointX;
},
touchend(e) {
this.isAni = false;
// console.log("touchend:手指离开屏幕的一瞬间触发");
// 判断边界问题
if (this.x >= 0) this.x = 0;
if (this.x <= this.$el.clientWidth - this.$refs.container.clientWidth)
this.x = this.$el.clientWidth - this.$refs.container.clientWidth;
// 整页翻
this.x =
Math.round(this.x / this.$el.clientWidth) * this.$el.clientWidth +
16 * Math.round(this.x / this.$el.clientWidth);
},
touchcancel(e) {
// console.log("touchcancel:触摸事件被迫取消(结束)")
}
}
};
</script>