每日一练 CSS变量的妙用

111 阅读1分钟

当再写CSS时使用百分比设置比如宽度,那么就不能准确的拿到元素的实际宽度

这时可以使用CSS变量结合JS来取值

主要方法setProperty

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
     height: var(--w);
    }
  </style>
</head>
<body>
  <div class="box">
    fsdfsdfsdf
  </div>
  <script>
    const box = document.querySelector('.box')
    console.log([box]);
    const w = box.clientWidth
    box.style.setProperty('--w',w+'px')
  </script>
</body>
</html>