<!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">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<title>拖拽</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
background: red;
100px;
height: 100px;
position: absolute;
}
</style>
</head>
<body>
<div id="app">
<div id="box" v-drag.l.t="flag"></div>
</div>
<script>
Vue.directive("drag",(el,{modifiers,value})=>{
let{l,t}=modifiers;
el.addEventListener("mousedown",handleDownCb)
let disX,disY;
function handleDownCb(e){
disX=e.offsetX;
disY=e.offsetY;
document.addEventListener("mousemove",handleMoveCb);
document.addEventListener("mouseup",handleUpCb);
}
function handleMoveCb(e){
let x=e.clientX-disX;
let y=e.clientY-disY;
if((l&&t) && value){
el.style.left=x+"px";
el.style.top=y+"px";
return;
}
if(l&&value){
el.style.left=x+"px";
return;
}
if(t&&value){
el.style.top=y+"px";
return;
}
}
function handleUpCb(){
document.removeEventListener("mousemove",handleMoveCb);
document.removeEventListener("mouseup",handleUpCb);
}
})
let vm=new Vue({
el:"#app",
data:{
flag:true
}
})
</script>
</body>
————————————————
原文链接:https://blog.csdn.net/Pluto_zk/article/details/100128288