实现dialog在页面随意拖拽
1.先建一个文件如图所示:
文件名:dialog-directive.js
文件内容:
import Vue from 'vue'
// v-dialogDrag: 弹窗拖拽Vue.directive('dialogDrag', {bind(el, binding, vnode, oldVnode) {// 获取拖拽内容的头部const dialogHeaderEl = el.querySelector('.el-dialog__header')// 获取拖拽整体const dragDom = el.querySelector('.el-dialog') || el.querySelector('.ele-form-dialog')//( rrc-dialog是我自己封装的组件 如果使用element组件应写成.el-dialog)dialogHeaderEl.style.cursor = 'move'
// 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)// const sty = window.getComputedStyle(dragDom, null)// 鼠标按下事件dialogHeaderEl.onmousedown = (e) => {// 鼠标按下,计算当前元素距离可视区的距离 (鼠标点击位置距离可视窗口的距离)const disX = e.clientX - dialogHeaderEl.offsetLeftconst disY = e.clientY - dialogHeaderEl.offsetTop// 获取到的值带px 正则匹配替换let styL, styT// 在ie中 第一次获取到的值为组件自带50% 移动之后赋值为pxif (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 // 计算出从上往下拖动了多少let finallyL = l + styLlet finallyT = t + styT// 边界值判定 注意clientWidth scrollWidth区别 要减去之前的top left值// dragDom.offsetParent表示弹窗阴影部分if (finallyL < 0) {finallyL = l + styL} else if (finallyL > dragDom.offsetParent.clientWidth - dragDom.clientWidth - dragDom.offsetParent.offsetLeft) {finallyL = dragDom.offsetParent.clientWidth - dragDom.clientWidth - dragDom.offsetParent.offsetLeft}if (finallyT < 0) {finallyT = t + styT} else if (finallyT > dragDom.offsetParent.clientHeight - dragDom.clientHeight - dragDom.offsetParent.offsetLeft) {(finallyT = dragDom.offsetParent.clientHeight - dragDom.clientHeight - dragDom.offsetParent.offsetLeft)}// 移动当前元素dragDom.style.left = `${finallyL}px`dragDom.style.top = `${finallyT}px`}document.onmouseup = function(e) {document.onmousemove = nulldocument.onmouseup = null}}}})
2.在main.js中引入
import '@/util/dialog-directive'
3.在dialog组件中使用v-dialogDrag
<el-dialog title="派工受阻" :visible.sync="dispatchStopDialog" width="40%" :show-close="false" v-dialogDrag><el-form :model="forms" ref="forms" :rules="formRules"><el-form-item label="受阻原因" label-width="120px" prop="failReason" ><el-select v-model="forms.failReason" style="width: 68%" placeholder="受阻原因" size="small" @change="$forceUpdate();blockedReasoncheck()"><el-option v-for="item in dispatchReasonList" :key="item.key" :label="item.value" :value="item.key" ></el-option></el-select></el-form-item></el-form><div slot="footer" class="dialog-footer"><el-button type="info" @click="dispatchStopOff">取 消</el-button><el-button type="primary" @click="isOk(forms)">确 定</el-button></div>
</el-dialog>
就可以实现dialog在页面随意拖拽。