HTML拖拽

拖拽的流程:鼠标按下(mousedown)→鼠标移动(mousemove)→鼠标松开(moveup)

需要理解的几个api:

  • clientX/clientY: 相对于浏览器视窗内的位置坐标(不包括浏览器收藏夹和顶部网址部分)
  • pageX/pageY: 该属性会考虑滚动,如果鼠标相对浏览器左边距离为100px,并向左滚动了200px,则pageX返回300px
  • screenX/screenY:相对于屏幕的距离
  • offsetLeft/offsetTop: 当前元素距离父辈元素的距离

具体实现:

et box  = document.getElementById('box1')

box.onmousedown = (e) =>{

   //获取鼠标在移动元素上的位置

    let x = e.clientX - box.offsetLeft

    let y = e.clientY - box.offsetTop

   document.onmousemove = (event) => {

         let left = event.clientX - x  //当前元素左边界距离当前视窗的位置

         let top = event.clientY - y //当前元素上边界距离当前视窗的位置

         box.style.left = left + 'px'

         box.style.top = top + 'px'

    }

    document.onmouseup = () => {

        document.onmousemove = null

        document.onmouseup = null

    }

}

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