在项目开发过程中,需要支持dialog弹窗可拖拽,则需要对dialog添加指令。具体操作说明如下:
(1)在用于存放指令的文件夹内,新建拖拽指令文件夹,例如命名为:el-dragDialog,如下所示:
el-dragDialog/index.js文件代码,如下示:
1 import drag from './drag' 2 3 const install = function(Vue) { 4 Vue.directive('el-drag-dialog', drag) 5 } 6 7 if (window.Vue) { 8 window['el-drag-dialog'] = drag 9 Vue.use(install); // eslint-disable-line 10 } 11 12 drag.install = install 13 export default drag
el-dragDialog/drag.js文件代码,如下示:
1 export default{ 2 bind(el, binding, vnode) { 3 const dialogHeaderEl = el.querySelector('.el-dialog__header') 4 const dragDom = el.querySelector('.el-dialog') 5 dialogHeaderEl.style.cssText += ';cursor:move;' 6 dragDom.style.cssText += ';top:0px;' 7 8 // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null); 9 const getStyle = (function() { 10 if (window.document.currentStyle) { 11 return (dom, attr) => dom.currentStyle[attr] 12 } else { 13 return (dom, attr) => getComputedStyle(dom, false)[attr] 14 } 15 })() 16 17 dialogHeaderEl.onmousedown = (e) => { 18 // 鼠标按下,计算当前元素距离可视区的距离 19 const disX = e.clientX - dialogHeaderEl.offsetLeft 20 const disY = e.clientY - dialogHeaderEl.offsetTop 21 22 const dragDomWidth = dragDom.offsetWidth 23 const dragDomheight = dragDom.offsetHeight 24 25 const screenWidth = document.body.clientWidth 26 const screenHeight = document.body.clientHeight 27 28 const minDragDomLeft = dragDom.offsetLeft 29 const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth 30 31 const minDragDomTop = dragDom.offsetTop 32 const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight 33 34 // 获取到的值带px 正则匹配替换 35 let styL = getStyle(dragDom, 'left') 36 let styT = getStyle(dragDom, 'top') 37 38 if (styL.includes('%')) { 39 styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100) 40 styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100) 41 } else { 42 styL = +styL.replace(/\px/g, '') 43 styT = +styT.replace(/\px/g, '') 44 } 45 46 document.onmousemove = function(e) { 47 // 通过事件委托,计算移动的距离 48 let left = e.clientX - disX 49 let top = e.clientY - disY 50 51 // 边界处理 52 if (-(left) > minDragDomLeft) { 53 left = -minDragDomLeft 54 } else if (left > maxDragDomLeft) { 55 left = maxDragDomLeft 56 } 57 58 if (-(top) > minDragDomTop) { 59 top = -minDragDomTop 60 } else if (top > maxDragDomTop) { 61 top = maxDragDomTop 62 } 63 64 // 移动当前元素 65 dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;` 66 67 // emit onDrag event 68 vnode.child.$emit('dragDialog') 69 } 70 71 document.onmouseup = function(e) { 72 document.onmousemove = null 73 document.onmouseup = null 74 } 75 } 76 } 77 }
(2)在main.js中引入该指令:
// 拖拽弹 import elDragDialog from './directive/el-dragDialog/index';窗 Vue.use(elDragDialog);
(3)在需要支持拖拽的的dialog中,加入指令:v-el-drag-dialog