1.首先在src目录下建立一个指令文件夹及文件
2.进入drag.js,复制下面代码
export const drag = {
inserted(el) {
let oDiv = el
// 左边距最大值
let maxLeft = el.parentNode.clientWidth - el.clientWidth
// 上边距最大值
let maxTop = el.parentNode.clientHeight - el.clientHeight
oDiv.onmousedown = function (e) {
// 鼠标按下,计算当前元素距离可视区的距离
let disX = e.clientX - oDiv.offsetLeft
let disY = e.clientY - oDiv.offsetTop
document.onmousemove = function (e) {
// 获取到鼠标拖拽后的横向位移(距离父级元素)
let l = e.clientX - disX
// 获取到鼠标拖拽后的纵向位移(距离父级元素)
let t = e.clientY - disY
oDiv.style.left = l + 'px'
oDiv.style.top = t + 'px'
if (e.clientX - disX <= 0) {
oDiv.style.left = 0 + 'px'
}
if (e.clientY - disY <= 0) {
oDiv.style.top = 0 + 'px'
}
if (e.clientX - disX >= maxLeft) {
oDiv.style.left = maxLeft + 'px'
}
if (e.clientY - disY >= maxTop) {
oDiv.style.top = maxTop + 'px'
}
}
// 松开事件后,移除事件
document.onmouseup = function () {
document.onmousemove = null
document.onmouseup = null
}
}
}
}
3.进入main.js文件,导入drag.js ,并注册指令
import {drag} from './directives/drag'
Vue.directive('drag',drag)
4. 使用,在dom标签上添加 v-drag指令,且被添加指令的标签,需要加上position: absolute;即可生效。代码如下:
<template>
<div class="content">
<div class="hello" v-drag>
// 加上v-drag 指令
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<style scoped>
.content{
width: 1000px;
height: 1000px;
border: 1px solid red;
margin: 0 auto;
position: relative;
}
.hello{
width: 100px;
height: 100px;
background: red;
border-radius: 50%;
border: 2px solid yellowgreen;
position: absolute; //必须加上这个
}
</style>
5.效果