Vue-custom instruction to achieve page div drag and drop function

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js"></script>
	</head>
	<body>
		<!-- 为了可移动,position属性设置成绝对定位 -->
		<div class="box" v-drag="greet" style="width: 200px;height: 300px;background-color: lightcoral;position: absolute;"></div>
	</body>
	<script>
		const vm = new Vue({
     
     
			el:".box",
			methods:{
     
       //接受传过来的位置数据
			  greet(val){
     
     
			    
			  }
			},
			directives: {
     
     
			      drag: {
     
     //drag自定义指令
			        bind: function (el, binding) {
     
     
			          let odiv = el;//el 当前元素
			          odiv.onmousedown = (e) => {
     
     //e是当鼠标按下时,返回的对象。包含点击的位置等等属性
			            e.preventDefault();//取消默认事件,可不加
			            let disX = e.clientX - odiv.offsetLeft;//获取当前div距左侧边界距离
			            let disY = e.clientY - odiv.offsetTop;//获取当前div距头部边界距离
			            let left = null;
			            let top = null;
			 
			            //将此时的位置传出去
			            binding.value({
     
     x: odiv.offsetLeft, y: odiv.offsetTop})
			 
			            document.onmousemove = (e) => {
     
     //e是当鼠标移动时,返回的对象。包含拖动时等等属性
			              e.stopPropagation()
			              //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
			              left = e.clientX - disX;
			              top = e.clientY - disY;
			              //移动当前元素
			              odiv.style.left = left + 'px';
			              odiv.style.top = top + 'px';
			              //将此时的位置传出去
			              // binding.value({x:left,y:top})
			            }
			            document.onmouseup = (e) => {
     
     
			              document.onmousemove = null;
			              document.onmouseup = null;
			            };
			          };
			        }
			      }
			    }
		})
	</script>
</html>

Mainly two events onmousedown and onmousemove

Reprinted source

Guess you like

Origin blog.csdn.net/qq_36008278/article/details/114828432