Skip to content
html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html,body {
      height: 500%;
    }

    #box1 {
      margin-top: 100px;
      width: 100px;
      height: 100px;  
      background-color: pink;
      position: absolute;
      cursor: move;
    }
  </style>
</head>
<body>
  <div id="box1"></div>

  <script>
    /*
      解决鼠标移动过快脱离盒子
        1.IE/FireFox支持 Google不支持
          this.setCapture() 把鼠标和盒子绑定到一起直到鼠标抬起或document.releaseCapture()被调用 
          this.releaseCapture() 把鼠标和盒子解绑

        2.不给盒子绑定鼠标移动事件,绑定给document
          如果不基于DOM2给docyment绑定事件方法, 那么document就不能再绑定其他事件
    */
    function move (e) {
      const { pageX, pageY } = e

      const x = pageX
      const y = pageY

      let left = x - this.x + this.left
      let top = y - this.y + this.top

      const { clientWidth, clientHeight } = document.documentElement
      const minLeft = 0
      const minTop = 0
      const maxLeft = clientWidth - this.offsetWidth
      const maxTop = clientHeight - this.offsetHeight

      // 边界判断
      top = top < minTop
        ? minTop 
        : top > maxTop
            ? maxTop 
            : top

      left = left < minLeft 
        ? minLeft 
        : left > maxLeft 
            ? maxLeft 
            : left

      const marginTop = window.getComputedStyle(this).marginTop.slice(0, -2) * 1
      console.log(marginTop)

      this.style.top = `${ top - marginTop }px`
      this.style.left = `${ left }px`
    }

    function mouseUp () {
      document.onmousemove = null
    }
    
    function mouseDown (e) {
      const { left, top } = this.getBoundingClientRect()
      const { pageX, pageY } = e

      // 鼠标按下时鼠标在 HTML 中的坐标
      this.x = pageX
      this.y = pageY
      // 鼠标按下时盒子在 HTML 中的坐标
      this.left = left
      this.top = top

      document.onmousemove = move.bind(this)
      this.onmouseup = mouseUp
    }

    box1.onmousedown = mouseDown
  </script>
</body>
</html>