美文网首页
JavaScript 操作 CSS 变量

JavaScript 操作 CSS 变量

作者: 思念LY | 来源:发表于2020-07-17 13:33 被阅读0次
<!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>

相关文章

网友评论

      本文标题:JavaScript 操作 CSS 变量

      本文链接:https://www.haomeiwen.com/subject/ehdghktx.html