使用自定义拖拽指令实现el-draw宽(高)可拖拽
一、问题引入
场景:el-draw抽屉高度(宽度)可拖拽
二、解决方案
使用vue指令,el-draw打开后,插入一个元素,绑定鼠标事件实现拖拽
主要代码如下
/** * el-drawer 拖拽高度指令 */ Vue.directive('el-drawer-drag-height', { bind(el, binding, vnode, oldVnode) { const drawerEle = el.querySelector('.el-drawer') // 创建触发拖拽的元素 const dragItem = document.createElement('div') // 将元素放置到抽屉的左边边缘 dragItem.style.cssText = 'height: 5px;width: 100%;cursor: s-resize;position: absolute;top: 0;' drawerEle.append(dragItem) const moveCallback = function(e){ // e.preventDefault(); // e.stopPropagation(); // 获取鼠标距离浏览器上边缘的距离 let realHeight = document.body.clientHeight - e.pageY const height30 = document.body.clientHeight * 0.4 const height80 = document.body.clientHeight * 1 // 高度不能小于 40% realHeight = realHeight > height80 ? height80 : realHeight < height30 ? height30 : realHeight drawerEle.style.height = realHeight + 'px' } dragItem.addEventListener('mousedown', () => { // 拖拽时禁用文本选中 document.body.style.userSelect = 'none' document.addEventListener('mousemove', moveCallback) document.addEventListener('mouseup',()=>{ // 拖拽时结束时,取消禁用文本选中 document.body.style.userSelect = 'initial' document.removeEventListener('mousemove', moveCallback) // document.removeEventListener('mouseup') }) }) } })