<! DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Exercise: Custom instruction instance (element drag)</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
#app div{
width: 100px;
height: 100px;
position:absolute;
}
#app .hello{
background-color:red;
top:0;
left:0;
}
#app .world{
background-color:blue;
top:0;
right:0;
}
</style>
</head>
<body>
<div id="app">
<div class="hello" v-drag>itapp {{msg}}</div>
<button type="button" @click="changeMsg()">Change the MSG</button>
</div>
<script>
// Vue.directive('drag',{});
// Bind update hook function can be called
// bind: the directive is called when it is first bound to an element. It is called only once to perform initialization
Vue.directive('drag'.function(el){
console.log('kkkkk');
el.onmousedown=function(e){
// Get the distance between the mouse click and the left and top of the div: mouse position -div position
// var disX=e.clientX-el.offsetLeft; //e.offsetX
// var disY=e.clientY-el.offsetTop; // e.offsetY
var disX = e.offsetX;
var disY = e.offsetY;
To prevent the mouse from moving out of the div, use document.onmousemove
document.onmousemove=function(e){
// Get the position of the moved div: mouse position -disx /disY
var l=e.clientX-disX;
var t=e.clientY-disY;
el.style.left=l+'px';
el.style.top=t+'px';
}
// Stop moving
document.onmouseup=function(e){
document.onmousemove=null;
document.onmouseup=null; }}});var vm=new Vue({
el:'#app'.data: {msg:'welcome to itapp'.username:'alice'
},
methods: {changeMsg(){
this.msg='Welcome to custom Instruction Instance (Element drag)'}}});</script>
</body>
</html>
Copy the code