// 拖拽元素 改变高度 自定义指令 export const dragHeight = (el: any, binding: any) => { el.style.position = 'relative' let isPress = false // 最小宽度 let minHeight = 50 // 获取 drag-min-height 的值 if (binding.value) { minHeight = parseInt(binding.value, 10) } // 拖拽触发元素 const dragItem = document.createElement('div') dragItem.id = 'dragItem-height' // 将元素放置到抽屉的左边边缘 dragItem.style.cssText = 'height: 6px;width: 100%;cursor: n-resize;position: absolute;right: 0;bottom: 0;background-color: #ddd; display: none;' el.append(dragItem) // el 鼠标完全进入时,显示dragItem el.addEventListener('mouseenter', () => { if (isPress) { return } dragItem.style.display = 'block' }) // el 鼠标完全离开时,隐藏dragItem el.addEventListener('mouseleave', () => { if (isPress) { return } dragItem.style.display = 'none' }) // 鼠标按下时,开始拖拽 dragItem.onmousedown = () => { document.body.style.userSelect = 'none' // 获取el距离浏览器顶部的距离 const elTop = el.offsetTop isPress = true console.log('鼠标摁下') // 鼠标移动时,计算出拖拽的距离 document.onmousemove = (moveEvent) => { console.log('鼠标移动') let height = moveEvent.pageY - elTop - (binding.value || 1) if (height < minHeight) { height = minHeight } el.style.height = `${height}px` window.sessionStorage.setItem('drag-height', String(height)) // 将width赋值到CSS自定义属性 el.style.setProperty('--el-height', `${height}px`) // 阻止默认行为 return false } // 鼠标抬起时,结束拖拽 document.onmouseup = () => { console.log('鼠标抬起') document.onmousemove = null document.onmouseup = null document.body.style.userSelect = 'auto' isPress = false window.sessionStorage.removeItem('drag-height') } // 阻止默认行为 return false } }