1.utils文件夹下创建dialog.js文件
1 import Vue from 'vue'
2
3 // v-dialogDrag: 弹窗拖拽
4 Vue.directive('dialogDrag', {
5 bind(el, binding, vnode, oldVnode) {
6 const dialogHeaderEl = el.querySelector('.el-dialog__header')
7 const dragDom = el.querySelector('.el-dialog')
8 dialogHeaderEl.style.cursor = 'move'
9
10 // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
11 const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
12
13 dialogHeaderEl.onmousedown = (e) => {
14 // 鼠标按下,计算当前元素距离可视区的距离
15 const disX = e.clientX - dialogHeaderEl.offsetLeft
16 const disY = e.clientY - dialogHeaderEl.offsetTop
17
18 // 获取到的值带px 正则匹配替换
19 let styL, styT
20
21 // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
22 if (sty.left.includes('%')) {
23 styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
24 styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
25 } else {
26 styL = +sty.left.replace(/\px/g, '')
27 styT = +sty.top.replace(/\px/g, '')
28 }
29
30 document.onmousemove = function(e) {
31 // 通过事件委托,计算移动的距离
32 const l = e.clientX - disX
33 const t = e.clientY - disY
34
35 // 移动当前元素
36 dragDom.style.left = `${l + styL}px`
37 dragDom.style.top = `${t + styT}px`
38
39 // 将此时的位置传出去
40 // binding.value({x:e.pageX,y:e.pageY})
41 }
42
43 document.onmouseup = function(e) {
44 document.onmousemove = null
45 document.onmouseup = null
46 }
47 }
48 }
49 })
2.在main.js中全局引用
1 import './utils/dialog'
3.使用方法:给 el-dialog 添加 v-dialogDrag属性
1 <el-dialog v-dialogDrag></el-dialog>
来源:oschina
链接:https://my.oschina.net/u/4354143/blog/4306185