代码注意:
1、VUE自定义指令实现的方式,Vue.directive();
2、自定义指令使用的方式必须加v-;
3、拖拽功能思路:是把要拖拽的DOM的position:设置为absolute,这样就可以基于父窗口,或者根元素进行展示;
4、先在自定义指令中获取DOM元素,然后设置onmousedown事件,获取点击的位置坐标,然后就是小算法计算位置的问题;
5、移动使用document.onmousemove,不要使用el.onmousemove
6、移动结束后,即鼠标弹起后,要把onmousemove和onmouseup事件清除;
实现拖拽用到的属性
offsetLeft:距离参照元素左边界偏移量
offsetTop:距离参照元素上边界偏移量
clientWidth:此属性可以返回指定元素客户区宽度
clientHeight: 此属性可以返回指定元素客户区高度
clientX:事件被触发时鼠标指针相对于浏览器页面(或客户区)的水平坐标
clientY: 事件被触发时鼠标指针相对于浏览器页面(或客户区)的垂直坐标
onmousedown:鼠标按下事件
onmousemove: 鼠标滑动事件
onmouseup: 鼠标松开事件
pc端实现拖拽,看代码
<template>
<div class="about" v-drag></div>
</template>
<script>
export default {
name: "About",
directives: {
drag: {
inserted: el => {
console.log(el);
el.onmousedown = e => {
//按下鼠标事件
let ex = e.clientX - el.offsetLeft;
let ey = e.clientY - el.offsetTop;
el.onmousemove = e => {
//移动鼠标事件
let ex1 = e.clientX - ex;
let ey1 = e.clientY - ey;
el.style.left = ex1 + "px";
el.style.top = ey1 + "px";
};
};
el.onmouseup = function() {
//松开鼠标事件
el.onmousemove = null;
};
}
}
}
};
</script>
<style lang="scss" scoped>
.about {
width: 100px;
height: 100px;
background: blue;
position: absolute; //脱离文档流
}
</style>
移动端拖拽
<template>
<div class="about" v-drag></div>
</template>
<script>
export default {
name: "About",
directives: {
drag: {
inserted: el => {
var touch, disX, disY;
el.ontouchstart = e => {
if (e.touches) {
//有可能对象在e上也有可能对象在e.touches[0]上
touch = e.touches[0];
} else {
touch = e;
}
disX = touch.clientX - el.offsetLeft; //鼠标位置X减去元素距离左边距离(鼠标到元素左边的距离)
disY = touch.clientY - el.offsetTop; //鼠标位置Y减去距离顶部距离(鼠标到元素顶部的高度)
};
el.ontouchmove = e => {
if (e.touches) {
//有可能对象在e上也有可能对象在e.touches[0]上
touch = e.touches[0];
} else {
touch = e;
}
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = touch.clientX - disX;
let top = touch.clientY - disY;
//移动当前元素
el.style.left = left + "px";
el.style.top = top + "px";
e.preventDefault(); //阻止页面的滑动默认事件
};
el.ontouchend = function() {
// el.ontouchmove = null;
// el.ontouchend = null;
};
}
}
}
};
</script>
<style lang="scss" scoped>
.about {
width: 100px;
height: 100px;
background: blue;
position: absolute; //脱离文档流
}
</style>