有一个对话框,框的背景不是全屏的,只显示在除header和sidebar以外的地方,它需要拖动dialog弹框不能超出背景1.在components/common中创建directives.js,具体代码如下:importVuefrom'vue';//v-dialogDrag:弹出窗口拖动属性Vue.jsdirective('dialogDrag',{bind(el,binding,vnode,oldVnode){constdialogHeaderEl=el.querySelector('.el-dialog__header');constdragDom=el.querySelector('.el-dialog');dialogHeaderEl。style.cssText+=';cursor:move;'dragDom.style.cssText+=';top:0px;'//获取原始属性即domelement.currentStyleFirefoxGooglewindow.getComputedStyle(domelement,null);conststy=(()=>{if(window.document.currentStyle){return(dom,attr)=>dom.currentStyle[attr];}else{return(dom,attr)=>getComputedStyle(dom,false)[属性];}})()直径logHeaderEl.onmousedown=(e)=>{//当鼠标按下时,计算当前元素到可见区域的距离constdisX=e.clientX-dialogHeaderEl.offsetLeft;constdisY=e.clientY-dialogHeaderEl.offsetTop;constscreenWidth=document.body.clientWidth;//body的当前宽度constscreenHeight=document.documentElement.clientHeight;//可见区域高度(应该是身高,在某些环境下无法获取)constdragDomWidth=dragDom.offsetWidth;//对话框宽度constdragDomheight=dragDom.offsetHeight;//对话框高度constminDragDomLeft=dragDom.offsetLeft;constmaxDragDomLeft=screenWidth-dragDom.offsetLeft-dragDomWidth;constminDragDomTop=dragDom.offsetTop;constmaxDragDomTop=screenHeight-dragDom.offsetTop-dragDomheight;//获取带px正则匹配替换的值letstyL=sty(dragDom,'left');让styT=sty(dragDom,'top');//注意ie中第一次获取的值是组件本身的50%,移动后赋值给pxif(styL.includes('%')){styL=+document.body.clientWidth*(+styL.replace(/\%/g,'')/100);秒tyT=+document.body.clientHeight*(+styT.replace(/\%/g,'')/100);}else{styL=+styL.replace(/\px/g,'');styT=+styT.replace(/\px/g,'');};document.onmousemove=function(e){//通过事件委托,计算移动距离letleft=e.clientX-disX;让顶部=e。客户Y-disY;//边界处理if(-(left)>minDragDomLeft){left=-(minDragDomLeft);}elseif(left>maxDragDomLeft){left=maxDragDomLeft;}if(-(top)>minDragDomTop){top=-(minDragDomTop);}elseif(top>maxDragDomTop){top=maxDragDomTop;}//移动当前元素dragDom.style.cssText+=`;left:${left+styL}px;top:${top+styT}px;`;};文档.onmouseup=function(e){document.onmousemove=null;文档.onmouseup=null;};}}})2.然后在main.js中引入我们刚刚创建的directives.js文件//main.jsimport'./components/common/directives';3、最后找到我们需要拖拽的组件,在它的label中添加v-dialogDrag(自定义指令)代码如下://DragDialog.vue
