Newer
Older
smartwell_front / src / directives / drag-width / index.ts
liyaguang on 9 Jan 1 KB ‘设备运维’
// 拖拽元素 改变宽度 自定义指令
export const dragWidth = (el: any, binding: any) => {
  // console.log(el, binding)
  el.style.position = 'relative'
  let isPress = false
  // console.log(binding, 'binding')
  // 最小宽度
  let minWidth = 50
  // 获取 drag-min-width 的值
  if (binding.value) {
    minWidth = parseInt(binding.value, 10)
  }
  // 拖拽触发元素
  const dragItem = document.createElement('div')
  dragItem.id = 'dragItem-width'
  // 将元素放置到抽屉的左边边缘
  dragItem.style.cssText =  'height: 100%;width: 5px;cursor: w-resize;position: absolute;top: 0;right: 0;background-color: #ddd; display: none;z-index:99;'
  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 elLeft = el.offsetLeft
    isPress = true

    // 鼠标移动时,计算出拖拽的距离
    document.onmousemove = (moveEvent) => {
      let width = moveEvent.pageX - elLeft - (binding.value || 1)
      if (width < minWidth) {
        width = minWidth
      }
      el.style.width = `${width}px`
      // 将width赋值到CSS自定义属性
      el.style.setProperty('--el-width', `${width}px`)

      // 阻止默认行为
      return false
    }
    // 鼠标抬起时,结束拖拽
    document.onmouseup = () => {
      document.onmousemove = null
      document.onmouseup = null
      document.body.style.userSelect = 'auto'
      isPress = false
    }
    // 阻止默认行为
    return false
  }
}