classList i getComputedStyle

Wygląd strony: style i klasy - JavaScript na stronach WWW (HTML/CSS/JS)

`classList` ma metody `add`, `remove`, `toggle` i `contains`. Element może mieć wiele klas naraz (`warning big`). `element.style` widzi tylko styl wpisany do atrybutu `style`, a `getComputedStyle(element)` zwraca styl naprawdę użyty przez przeglądarkę, także ten z arkusza CSS i klas. Dlatego `style.color` jest pusty, a wyliczony kolor już nie.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>classList</title>
  <style>
    body { font-family: sans-serif; max-width: 36em; line-height: 1.4; }
    input, select, button, textarea { font: inherit; padding: 0.2em 0.4em; }
    table { border-collapse: collapse; }
    th, td { border: 1px solid #94a3b8; padding: 0.2em 0.6em; }

                    .warning { color: rgb(180, 83, 9); font-weight: bold; }
                    .big { font-size: 28px; }
  </style>
</head>
<body>
  <p id="note" class="warning">Uwaga: jutro sprawdzian!</p>
  <button id="big">big</button>
  <button id="warn">warning</button>
  <pre id="out"></pre>
  <script>
    const note = document.getElementById('note');

    function report() {
      document.getElementById('out').textContent = [
        'klasy: ' + [...note.classList].join(' '),
        'contains("big"): ' + note.classList.contains('big'),
        'style.color: "' + note.style.color + '"',
        'getComputedStyle color: ' + getComputedStyle(note).color,
        'getComputedStyle font-size: ' + getComputedStyle(note).fontSize,
      ].join('\n');
    }

    document.getElementById('big').addEventListener('click', () => {
      note.classList.toggle('big');
      report();
    });
    document.getElementById('warn').addEventListener('click', () => {
      if (note.classList.contains('warning')) note.classList.remove('warning');
      else note.classList.add('warning');
      report();
    });
    report();
  </script>
</body>
</html>

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript na stronach WWW·Zaloguj się, aby zapisać postęp na koncie.