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;
            };
        }
    }
})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值