forked from drone/command-center-dashboard

chenyao
2025-03-31 295eb3cc87aaa5176d64a4ef985cdad0bfefae9a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const drag = {
  mounted(el, binding) {
 
    const dragBox = document.querySelector('#' + binding.arg)
    //鼠标点击距离box盒子left的距离
    let spotToBoxLeft = 0
    let spotToBoxTop = 0
 
    const mouseupFun = (e) => {
      window.removeEventListener('mousemove', mousemoveFun)
      window.removeEventListener('mouseup', mouseupFun)
    }
 
    const mousemoveFun = (evt) => {
      console.log(66666);
      //获取body宽高,获取拖动盒子的宽高
      const {offsetWidth: bodyWidth, offsetHeight: bodyHeight} = document.body
      const {offsetWidth: boxWidth, offsetHeight: boxHeight} = dragBox
      //max取最大值,min取最小值
      const left = Math.max(evt.clientX - spotToBoxLeft, 0)
      const top = Math.max(evt.clientY - spotToBoxTop, 0)
      dragBox.style.left = Math.min(left, bodyWidth - boxWidth) + 'px'
      dragBox.style.top = Math.min(top, bodyHeight - boxHeight) + 'px'
    }
 
    el.__mousedownFun = (evt) => {
      //鼠标坐标减去 box盒子相对于父盒子body 的距离
      spotToBoxLeft = evt.clientX - dragBox.offsetLeft
      spotToBoxTop = evt.clientY - dragBox.offsetTop
      window.addEventListener('mousemove', mousemoveFun)
      window.addEventListener('mouseup', mouseupFun)
    }
    el.addEventListener('mousedown', el.__mousedownFun);
  },
 
  // 绑定元素的父组件卸载前调用
  beforeUnmount(el, binding,) {
    el.removeEventListener('mousedown', el.__mousedownFun)
  },
}
 
export default drag