elementui实现dialog拖拽

新建一个dialogDrag.js文件

import Vue from 'vue'
// v-dialogDrag: 弹出框拖拽属性
Vue.directive('dialogDrag', {
    bind(el, binding, vnode, oldVnde) {
        if (!binding.value) return
        const dialogHeaderEl = el.querySelector('.el-dialog__header')
        const dragDom = el.querySelector('.el-dialog')
        dialogHeaderEl.style.cssText += ';cursor:move;'
        dragDom.style.cssText += ';top:0px;'

        const sty = (function () {
            if (document.body.currentStyle) {
                return (dom, attr) => dom.currentStyle[attr]
            } else {
                return (dom, attr) => getComputedStyle(dom, false)[attr]
            }
        })()

        // 鼠标拖拽
        dialogHeaderEl.onmousedown = (e) => {
            const disX = e.clientX - dialogHeaderEl.offsetLeft
            const disY = e.clientY - dialogHeaderEl.offsetTop

            const screenWidth = document.body.clientWidth
            const screenHeight = document.documentElement.clientHeight

            const dragDomWidth = dragDom.offsetWidth
            const dragDomHeight = dragDom.offsetHeight

            const minDragDomLeft = dragDom.offsetLeft
            const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth

            const minDragDomTop = dragDom.offsetTop
            const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomHeight

            let styL = sty(dragDom, 'left')
            if (styL === 'auto') styL = '0px'
            let styT = sty(dragDom, 'top')
            if (styL.includes('%')) {
                styL = +document.body.clientWidth * (+styL.replace(/%/g, '') / 100)
                styT = +document.body.clientHeight * (+styL.replace(/%/g, '') / 100)
            } else {
                styL = +styL.replace(/px/g, '')
                styT = +styL.replace(/px/g, '')
            }

            document.onmousemove = function (e) {
                let left = e.clientX - disX
                let top = e.clientY - disY

                if (-(left) > minDragDomLeft) {
                    left = -(minDragDomLeft)
                } else if (left > maxDragDomLeft) {
                    left = maxDragDomLeft
                }

                if (-(top) > minDragDomTop) {
                    top = -(minDragDomTop)
                } else if (top > maxDragDomTop) {
                    top = maxDragDomTop
                }

                dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px`
            }

            document.onmouseup = function () {
                document.onmousemove = null
                document.onmouseup = null
            }
            return false
        }
    }
})

在main.js中引用

import './dialogDrag'

在vue中使用

<el-dialog v-dialogDrag="true">
<el-dialog>

你可能感兴趣的:(vue+elementui,vue)