实现代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="drop">拖动我</div>
  </body>
  <script>
    const dropEl = document.querySelector(".drop");
    let offsetX, offsetY;
    let isDroping = false;

    dropEl.addEventListener("mousedown", (e) => {
      let clineX = e.clientX,
        clineY = e.clientY;
      offsetX = clineX - dropEl.getBoundingClientRect().left;
      offsetY = clineY - dropEl.getBoundingClientRect().top;

      isDroping = true;
      dropEl.style.cursor = "grabbing";
    });

    document.addEventListener("mousemove", (e) => {
      if (isDroping) {
        const newX = e.clientX - offsetX;
        const newY = e.clientY - offsetY;

        dropEl.style.left = newX + "px";
        dropEl.style.top = newY + "px";
      }
    });

    document.addEventListener("mouseup", () => {
      isDroping = false;
      dropEl.style.cursor = "grab";
    });
  </script>
  <style>
    :root {
      --widthSize: 200px;
    }
    .drop {
      width: var(--widthSize);
      height: var(--widthSize);
      text-align: center;
      background: orange;
      line-height: var(--widthSize);
      padding: 20px;
      margin: 20px;
      user-select: none;
      position: relative;
    }
  </style>
</html>

本文链接:https://blog.smallhao.fun/?id=20 转载需授权!

分享到: