1. 程式人生 > 其它 >自定義v-draggable指定拖動el-dialog

自定義v-draggable指定拖動el-dialog

參考網頁——vue專案中常用自定義指令的使用 - smile_or - 部落格園 (cnblogs.com)

Vue自定義指令實現element-ui dialog拖拽調整位置和視窗大小_m0_43422403的部落格-CSDN部落格

0.需求

拖動el-dialog的標題才能拖動

右下角的關閉按鈕點選即關閉

1.解決

參照上面兩個網站

全域性掛指令

// src/directives/index.js

import draggable from './js/draggable.js';

const directives = {
  draggable
}

export default {
  install(Vue){
    Object.keys(directives).forEach(key
=>{ Vue.directive(key, directives[key]) }) } }

// src/directives/js/draggable.js

export default {
    // inserted: function (el) {
    //     console.log('Move Draggle', el.parentElement);
    bind(el, binding, vnode, oldVnode) {
        const dialogHeaderEl = el.querySelector('.el-dialog__header')
        const dragDom 
= el.querySelector('.el-dialog__wrapper') 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中 第一次獲取到的值為元件自帶50% 移動之後賦值為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) < 0 ? 0 : t + styT}px` } document.onmouseup = function (e) { document.onmousemove = null document.onmouseup = null } } } // } }
View Code

// main,js

// mixin是全域性混入,與這個沒關係。

2.使用

3.分析

這部分程式碼是獲取el-dialog標題元素與移動彈窗的定位關鍵

人生到處知何似,應似飛鴻踏雪泥。