# drag拖拽

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>拖拽</title>
    <style type="text/css">
      #box {
        position: fixed;
        left: 100px;
        top: 100px;
        padding: 5px;
        background: #f0f3f9;
        font-size: 12px;
      }
      #main {
        border: 1px solid #a0b3d6;
        background: white;
      }
      #bar {
        line-height: 24px;
        background: #beceeb;
        border-bottom: 1px solid #a0b3d6;
        padding-left: 5px;
        cursor: move;
      }
      #content {
        width: 420px;
        height: 250px;
        padding: 10px 5px;
      }
    </style>
  </head>

  <body>
    <div id="box" draggable="true">
      <div id="main">
        <div id="bar">拖拽</div>
        <div id="content">
          内容……
        </div>
      </div>
    </div>
    <script type="text/javascript">
    const box = document.getElementById('box')
    // 开始拖拽时鼠标跟拖拽元素位置的相差值
    let offset = {
      x: 0,
      y: 0
    }

    box.addEventListener("dragstart", function(event) {
      // 计算偏差s
      const rect = event.target.getBoundingClientRect()
      offset.x = event.clientX - rect.left
      offset.y = event.clientY - rect.top
      // 隐藏拖拽元素,必须异步处理
      setTimeout(() => {
        event.target.style.display = 'none'
      })
    }, false);

    box.addEventListener("dragend", function(event) {
      // 拖拽完成,显示
      event.target.style.display = 'block'
    }, false);

    // drop 的目标上触发
    document.addEventListener("dragover", function(event) {
      // 阻止默认行为以允许 drop
      event.preventDefault();
    }, false);

    document.addEventListener("drop", function(event) {
      // 阻止默认行为 (某些元素会作为链接打开)
      event.preventDefault();
      // 移动到鼠标的位置
      box.style.left = event.clientX - offset.x + 'px'
      box.style.top = event.clientY - offset.y + 'px'
    }, false);
    </script>
  </body>
</html>
更新时间: 2021年3月17日星期三下午4点35分