JavaScript 操作 CSS 变量

2020-07-17  本文已影响0人  思念LY
<!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>
上一篇 下一篇

猜你喜欢

热点阅读