首先我們分析下拖動的實現原理:
1:touchstart(移動端)
mousedown(pc端)
通過該事件我們可以知道鼠標或者手觸摸的起點位置clientX和clientY
同樣知道要拖動的div距離左上角的起點位置offsetLeft 和 offsetTop
2:
touchmove(移動端)
mousemove(pc端)
通過該事件我們可以知道鼠標或者手滑動的距離
移動距離 = 當前鼠標坐標 + 初始鼠標坐標
現在div應該在的坐標 = div的初始坐標 + 移動距離
代碼如下:
<template>
<div id="draggable">
<div id="webId">
<div>你的web頁面</div>
<!-- 如果碰到滑動問題,1.1 請檢查這里是否屬於同一點。 -->
<!-- 懸浮的HTML -->
<div
class="xuanfu"
id="moveDiv"
@mousedown="down"
@touchstart="down"
@mousemove="move"
@touchmove.prevent="move"
@mouseup="end"
@touchend="end"
>
</div>
</div>
<div>position.x:{{position.x}} -- position.y{{position.y}}</div>
<div>dx:{{dx}} --dy:{{dy}}</div>
<div>nx:{{nx}}--ny:{{ny}}</div>
<div>xPum:{{xPum}} --yPum:{{yPum}}</div>
<div>pageX:{{pageX}} --pagey:{{pagey}}</div>
</div>
</template>
<script>
export default {
data() {
return {
flags: false,
position: { x: 0, y: 0 }, //鼠標的橫縱坐標
pageX: "", //頁面可視區域的寬
pagey: "", //頁面可視區域的高
nx: "",
ny: "",
dx: "",
dy: "",
xPum: "",
yPum: ""
};
},
mounted() {
this.pageX = document.body.offsetWidth;
this.pagey = document.body.offsetHeight;
},
methods: {
// 實現移動端拖拽
down() {
this.flags = true; //是否開啟拖拽
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() {
if (this.flags) {
var touch;
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
this.nx = touch.clientX - this.position.x;
this.ny = touch.clientY - this.position.y;
this.yPum = this.dy + this.ny;
if (this.dx + this.nx <= 0) {
this.xPum = 0;
} else if(this.dx + this.nx >= this.pageX -100){
this.xPum = this.pageX - 100;
} else {
this.xPum = this.dx + this.nx;
}
if (this.dy + this.ny <= 0) {
this.yPum = 0;
} else if(this.dy + this.ny >= this.pagey -100){
this.yPum = this.pagey - 100;
} else {
this.yPum = this.dy + this.ny;
}
moveDiv.style.left = this.xPum + "px";
moveDiv.style.top = this.yPum + "px";
//阻止頁面的滑動默認事件;如果碰到滑動問題,1.2 請注意是否獲取到 touchmove
document.addEventListener(
"touchmove",
function() {
event.preventDefault();
},
false
);
}
},
//鼠標釋放時候的函數
end() {
this.flags = false;
}
}
};
</script>
<style>
.xuanfu {
/* 如果頁面報錯 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See <URL>; 請添加樣式 touch-action: none; */
touch-action: none;
height: 100px;
width: 100px;
/* 如果碰到滑動問題,1.3 請檢查 z-index。z-index需比web大一級*/
z-index: 999;
position: fixed;
top: 4.2rem;
right: 3.2rem;
border-radius: 0.8rem;
background-color: rgba(0, 0, 0, 0.55);
}
</style>
