之前項目有一個pc端項目使用的element ui前端框架,需要彈窗可以拖拽,element自帶的dialog是沒有這個功能的,度娘說可以寫自定義指令,特此記錄一下
廢話不多說上代碼:
1、新建directives.js文件
// 設置dialog拖動指令 // v-dialogDrag: 彈窗拖拽 Vue.directive("dialogDrag", { bind(el, binding, vnode, oldVnode) { const dialogHeaderEl = el.querySelector(".el-dialog__header"); const dragDom = el.querySelector(".el-dialog"); dialogHeaderEl.style.cursor = "move"; // 獲取原有屬性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null); const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null); dialogHeaderEl.onmousedown = e => { // 鼠標按下,計算當前元素距離可視區的距離 const disX = e.clientX - dialogHeaderEl.offsetLeft; const disY = e.clientY - dialogHeaderEl.offsetTop; // 獲取到的值帶px 正則匹配替換 let styL, styT; // 注意在ie中 第一次獲取到的值為組件自帶0% 移動之后賦值為px if (sty.left.includes("%")) { styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, "") / 100); styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, "") / 100); } else { styL = +sty.left.replace(/\px/g, ""); styT = +sty.top.replace(/\px/g, ""); } document.onmousemove = function(e) { // 通過事件委托,計算移動的距離 const l = e.clientX - disX; const t = e.clientY - disY; // 移動當前元素 dragDom.style.left = `${l + styL}px`; dragDom.style.top = `${t + styT}px`; // 將此時的位置傳出去 // binding.value({x:e.pageX,y:e.pageY}) }; document.onmouseup = function(e) { document.onmousemove = null; document.onmouseup = null; }; }; } });
2、將directives.js引入main.js
import '@/directive/directives.js'
3、指令使用
<el-dialog custom-class="grayDialog" v-dialogDrag width="70%" :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body> </el-dialog>
項目重啟,完成!!!