<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../js/vue.js"></script>
<style>
.div1,.div2{
width: 100px;
height: 100px;
position: absolute;
}
.div1{
background-color: blue;
top: 100px;
}
.div2{
background-color: red;
}
</style>
</head>
<body>
<div id="app">
<div class="div1" v-drag></div>
<div class="div2" v-drag></div>
</div>
</body>
<script>
Vue.directive('drag',el=>{
el.onmousedown=function(e){
console.log(e);
//计算出元素距离上边和左边的距离(鼠标点击的位置-元素的位置)
//这个应该能理解吧
var disX=e.clientX-el.offsetLeft;
var disY=e.clientY-el.offsetTop;
document.onmousemove = function(e){
//鼠标要按住不松开移动才行,松开就会触发onmouseup的事件
//计算出元素移动后的位置(鼠标位置-元素初始的disX/disY)
var l=e.clientX-disX;
var t=e.clientY-disY;
el.style.left=l+'px';
el.style.top=t+'px';
}
document.onmouseup=function(e){
document.onmousemove=null;
document.onmouseup=null;
el.style.left=l+'px';
el.style.top=t+'px';
}
}
})
new Vue({
el:'#app'
})
</script>
</html>