给标签绑定事件,组件标签需要.native修饰符
<Suspend
class="suspend_box"
@mousedown.native="down()"
@touchstart.prevent.native="down()"
@mousemove.native="move()"
@touchmove.prevent.native="move()"
@mouseup.native="end()"
@touchend.prevent.native="end()"
id="moveDiv"
/>
data中定义数据
data() {
return {
flags: false,
position: { x: 0, y: 0 },
nx: "",
ny: "",
dx: "",
dy: "",
xPum: "",
yPum: ""
};
},
定义方法
down() {
// console.log("手指按下");
this.flags = true;
let moveDiv = document.getElementById("moveDiv");
var touch;
// 判断屏幕上手指数量 如果多跟手指是个数组 否则是个对象
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
// 本地化手指每次按下的位置
this.position.x = touch.clientX;
this.position.y = touch.clientY;
// 获保存取自身左外边框到定位父级的左内边框的距离
this.dx = moveDiv.offsetLeft;
this.dy = moveDiv.offsetTop;
},
move() {
let moveDiv = document.getElementById("moveDiv");
// 在手指按下时候flags已经为true
if (this.flags) {
var touch;
// 70行
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
// clientX 当前手指位置距离当前body可视区域的x,y坐标
// this.position.x 手指按下时元素位置
//this.nx 元素每次相对于初始位置移动的坐标位置
this.nx = touch.clientX - this.position.x;
this.ny = touch.clientY - this.position.y;
this.xPum = this.dx + this.nx;
this.yPum = this.dy + this.ny;
moveDiv.style.left = this.xPum + "px";
moveDiv.style.top = this.yPum + "px";
}
},
//鼠标释放时候的函数
end() {
this.flags = false;
}
这时候因为没有阻止默认事件,拖拽会比较卡,而且会有一个报错
可以加一个**touch-action: none; **css属性,阻止所有的touch事件。