classList 和 cssText 这两个我以前没见过的东西

341 阅读1分钟

classList

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div class="aa bb">1</div>
<div class="aa bb">2</div>
<div class="aa bb">3</div>
<div class="aa bb">4</div>
<div class="aa bb">5</div>
<div class="aa bb">6</div>
<div class="aa bb">7</div>
<div class="aa bb">8</div>
</body>
</html>

<script>
  Array.from(document.getElementsByClassName('aa')).forEach(p => {
    p.classList.remove('bb');
    console.log(p.classList)
  });
</script>

结果:

  

cssText


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    #box {
      width: 100px;
      height: 100px;
      background: #000;
      color: #ffffff;
    }
  </style>
</head>
<body>
<div id="box">1</div>
</body>
</html>

<script>
  document.getElementById('box').style.cssText = `background: #fff; color: #000; font-size: 50px`;
</script>

结果: