第24题 实现一个拖拽

    <style>
      html, body {
        margin: 0;
        height: 100%;
      }
      #box {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        top: 100px;
        left: 100px;
      }
    </style>
    <div id="box"></div>
    window.onload = function () {
      var box = document.getElementById('box');
      box.onmousedown = function (ev) {
        var oEvent = ev || window.event; // 兼容火狐,火狐下没有window.event
        var distanceX = oEvent.clientX - box.offsetLeft; // 鼠标到可视区左边的距离 - box到页面左边的距离
        var distanceY = oEvent.clientY - box.offsetTop;
        document.onmousemove = function (ev) {
          var oEvent = ev || window.event;
          var left = oEvent.clientX - distanceX;
          var top = oEvent.clientY - distanceY;
          if (left <= 0) {
            left = 0;
          } else if (left >= document.documentElement.clientWidth - box.offsetWidth) {
            left = document.documentElement.clientWidth - box.offsetWidth;
          }
          if (top <= 0) {
            top = 0;
          } else if (top >= document.documentElement.clientHeight - box.offsetHeight) {
            top = document.documentElement.clientHeight - box.offsetHeight;
          }
          box.style.left = left + 'px';
          box.style.top = top + 'px';
        }
        box.onmouseup = function () {
          document.onmousemove = null;
          box.onmouseup = null;
        }
      }
    }
Last Updated:
Contributors: leeguooooo