模板部分
<template><div class="home"><div id="box" v-drag></div></div></template>
自定义指令
<script>// @ is an alias to /srcexport default {name: "Home",data() {return {}},directives: {drag: {// 指令的定义inserted: function(el) {// el.drag();console.log(el);//获取元素// var dv = document.getElementById("dv");let x = 0;let y = 0;let l = 0;let t = 0;let isDown = false;//鼠标按下事件el.onmousedown = function(e) {//获取x坐标和y坐标x = e.clientX;y = e.clientY;//获取左部和顶部的偏移量l = el.offsetLeft;t = el.offsetTop;//开关打开isDown = true;//设置样式el.style.cursor = "move";};//鼠标移动window.onmousemove = function(e) {if (isDown == false) {return;}//获取x和ylet nx = e.clientX;let ny = e.clientY;//计算移动后的左偏移量和顶部的偏移量let nl = nx - (x - l);let nt = ny - (y - t);el.style.left = nl + "px";el.style.top = nt + "px";};//鼠标抬起事件el.onmouseup = function() {//开关关闭isDown = false;el.style.cursor = "default";};}}}};</script>
样式部分
<style lang="scss" scoped>#box {width: 60px;height: 60px;background-color: darkorange;border-radius: 50%;position: absolute;//脱离文档流}</style>
