此次是利用vue的自定義指令實現方塊拖拽vue
Vue.directive(指令名稱,function(參數){ this.el -> 原生DOM元素 });
拖拽:元素onmousedown中包括document.onmousemove和document.onmouseupthis
結構:code
<div id="box"> <div v-drag :style="{width:'100px', height:'100px', background:'blue', position:'absolute', right:0, top:0}"></div> <div v-drag :style="{width:'100px', height:'100px', background:'red', position:'absolute', left:0, top:0}"></div> </div>
script:ip
Vue.directive('drag',function(){ var oDiv=this.el; oDiv.onmousedown=function(ev){ var x=ev.pageX-oDiv.offsetLeft; var y=ev.pageY-oDiv.offsetTop; document.onmousemove=function(ev){ var l=ev.pageX-x; var t=ev.pageY-y; oDiv.style.left=l+'px'; oDiv.style.top=t+'px'; } document.onmouseup=function () { document.onmousemove=null; document.onmouseup=null; } } }) window.onload=function(){ var vm=new Vue({ data:{ } }).$mount('#box') }