首页JSJS实现简单的拖拽效果

JS实现简单的拖拽效果

分类JS时间2024-12-14 20:20:01发布RustStream浏览97
摘要:实现代码: <!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></html><!--autointro-->...

实现代码:

<!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 转载需授权!

分享到:

Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

JavaScriptHTML
Vue延迟渲染(defer)优化 消除异步函数的传染性

游客 回复需填写必要信息
召唤伊斯特瓦尔