点击移动盒子

 创建div

设置类名

 () => (
      <>
        
移动盒子
)

准备接收dom

let moveDivBOX = ref()

钩子函数中获取dom

   // 获取dom
    onMounted(() => {
      moveDivBOX.value = document.querySelector('#moveBox') as HTMLDivElement
    })

设置鼠标按下事件

 nextTick(() => {
      moveDivBOX.value?.addEventListener('mousedown', mouseDown)
    })

按下之后触发

  //按下元素距离顶部和左侧的位置,记录
      let x = e.clientX - moveDivBOX.value!.offsetLeft
      let y = e.clientY - moveDivBOX.value!.offsetTop

并注册鼠标移动事件和鼠标抬起事件

移动后的坐标赋值给定位style

        moveDivBOX.value!.style.left = e.clientX - x + 'px'
        moveDivBOX.value!.style.top = e.clientY - y + 'px'

鼠标抬起触发移除事件,移除mousemove事件

const mouseDown = (e: MouseEvent) => {
      //按下元素距离顶部和左侧的位置,记录
      let x = e.clientX - moveDivBOX.value!.offsetLeft
      let y = e.clientY - moveDivBOX.value!.offsetTop
      console.log(111)
      const mouseMove = (e: MouseEvent) => {
        moveDivBOX.value!.style.left = e.clientX - x + 'px'
        moveDivBOX.value!.style.top = e.clientY - y + 'px'
      }
      moveDivBOX.value?.addEventListener('mousemove', mouseMove)
      document.addEventListener('mouseup', () => {
        moveDivBOX.value?.removeEventListener('mousemove', mouseMove)
      })
    }

点击移动盒子_第1张图片

你可能感兴趣的:(html,css,javascript)