移动端可拖拽div
前言
移动端@touchstart @touchmove @touchend实际上对应PC得@mousedown @mousemove @mouseup
html
<div
class="cart-wrapper"
@touchstart="gotouchstart"
@touchmove="gotouchmove"
@touchend="gotouchend"
id="ktz"
>
可拖拽div
</div>
定义变量
return {
clientX: 0,
clientY: 0,
offsetLeft: 0,
offsetTop: 0,
isDown: false,
};
js
//点击开始触发事件 获取当前所在坐标
gotouchstart(e) {
console.log(e);
this.clientX = e.changedTouches[0].clientX;
this.clientY = e.changedTouches[0].clientY;
this.offsetLeft = e.target.offsetLeft;
this.offsetTop = e.target.offsetTop;
this.isDown = true;
},
//开始拖动div 不断获取新坐标并赋值
gotouchmove(e) {
console.log(e.changedTouches[0]);
var a = e.changedTouches[0];
console.log("wawawa");
if (this.isDown) {
const x = a.clientX;
const y = a.clientY;
let nx = x - (this.clientX - this.offsetLeft);
let ny = y - (this.clientY - this.offsetTop);
// document.getElementById("ktz").style.left = nx + "px"; //只允许上下拖动
// var height = document.getElementById("inner").offsetHeight; //获取外层div 得高度 可做判断对移动位置加以限制
if (ny >= 0) {
document.getElementById("ktz").style.top = ny + "px";
}
} else {
return;
}
},
//结束
gotouchend(e) {
console.log("hahah ");
this.$nextTick(() => {
this.isDown = false;
});
},
css
样式随意
.cart-wrapper {
position: absolute;
left: 0;
width: 118px;
height: 104px;
background: #e7ebef;
z-index: 999;
}