JavaScript 操作 CSS 变量

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>按下鼠标 元素跟着鼠标移动(使用 CSS 变量)</title>
    <style>
      :root {
        --mouse-x: 0;
        --mouse-y: 0;
      }
      .title {
        padding: 10px;
        width: 100px;
        border: 1px solid #000;
        margin-top: calc(var(--mouse-y) * 1px);
        margin-left: calc(var(--mouse-x) * 1px);
      }
    </style>
  </head>
  <body>
    <div class="title">test</div>
  </body>
  <script>
    const docStyle = document.documentElement.style;
    const box = document.getElementsByClassName("title")[0];
    box.addEventListener("mousedown", (e) => move());
    box.addEventListener("mouseup", (e) => cancleMove());
    function changeBoxPosition(e) {
      // JavaScript 操作 CSS 变量
      docStyle.setProperty("--mouse-x", e.clientX - 10);
      docStyle.setProperty("--mouse-y", e.clientY - 10);
    }
    function move() {
      document.addEventListener("mousemove", changeBoxPosition);
    }
    function cancleMove() {
      document.removeEventListener("mousemove", changeBoxPosition);
    }
  </script>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。