vue 自定义指令弹窗鼠标拖拽弹窗表头,弹窗移动

拖拽整个过程由三个事件完成

  1. 鼠标按下事件 onmousedown
  2. 鼠标移动事件 onmousemove
  3. 鼠标抬起事件 onmouseup
Vue.directive('drag', {
    inserted:function(el) {
        const dragDom = el.querySelector('.move'); //鼠标拖动的区域添加move
        dragDom.style.cursor = 'move'; //鼠标移动的样式
        dragDom.onmousedown = (e) => {
            //鼠标按下时,element-ui中下拉框展开的全部收起(若弹窗种有element-ui的下拉菜单)
            //没有element-ui组件可忽略
            const MousedownEvent = new Event('mousedown', {bubbles:true});
            const MouseupEvent = new Event('mouseup', {bubbles:true});
            document.body.click();
            document.dispatchEvent(MousedownEvent);
            document.dispatchEvent(MouseupEvent);
            // 鼠标按下,计算当前元素距离可视区的距离
            const disX = e.clientX - el.offsetLeft;
            const disY = e.clientY - el.offsetTop;
            document.onmousemove = (e)=>{
                //超出上下屏幕区域终止
                if(e.clientY < 0 || e.clientY > document.body.clientHeight) return;
                //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
                let left = e.clientX - disX;
                let top = e.clientY - disY;
                //移动当前元素
                el.style.position = 'fixed';
                el.style.left = left + 'px';
                el.style.top = top + 'px';
            };
            document.onmouseup = (e) => {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        }
    }
})

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