<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
</head>
<style>
#app {
position: relative;
}
.box {
position: absolute;
width: 200px;
height: 200px;
}
.box1 {
background: red;
left: 20px;
top: 20px;
}
.box2 {
background: greenyellow;
left: 220px;
top: 220px;
}
.box3 {
background: green;
left: 20px;
top: 220px;
}
</style>
<body>
<div id="app">
<button @click="canDrag = !canDrag">Drag: {{canDrag}}</button>
<div class="box box1" v-drag.limit="canDrag"></div>
<div class="box box2" v-drag="canDrag"></div>
<div class="box box3" v-drag="canDrag"></div>
</div>
</body>
<script>
Vue.directive('drag', {
bind(el, {
value,
modifiers
}) {
let isDragStart = false;
let disX = 0;
let disY = 0;
// el增加自定义属性
el.canDrag = value
// 鼠标按下
el.addEventListener('mousedown', e => {
if (!el.canDrag) return;
let disX = e.clientX - el.offsetLeft;
let disY = e.clientY - el.offsetTop;
isDragStart = true;
e.preventDefault();
});
// 鼠标移动
document.addEventListener('mousemove', e => {
if (isDragStart) {
let x = e.clientX - disX;
let y = e.clientY - disY;
// 修饰符判断
if (modifiers.limit) {
if (x < 0) {
x = 0;
} else if (x > document.documentElement.clientWidth - el.offsetWidth) {
x = document.documentElement.clientWidth - el.offsetWidth;
}
if (y < 0) {
y = 0;
} else if (y > document.documentElement.clientHeight - el.offsetHeight) {
y = document.documentElement.clientHeight - el.offsetHeight;
}
}
el.style.left = x + 'px';
el.style.top = y + 'px';
}
});
// 鼠标抬起
document.addEventListener('mouseup', e => {
isDragStart = false;
})
},
componentUpdated(el, {
value
}) {
// console.log(value)
el.canDrag = value
}
})
let app = new Vue({
el: '#app',
data: {
canDrag: false
}
});
</script>
</html>
网友评论