Zmienne CSS i suwak

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

Zmienna CSS (`--size`, `--hue`) to wartość, z której korzysta wiele reguł stylu. Skrypt ustawia ją jednym wywołaniem `style.setProperty('--hue', 200)`, a wszystkie elementy, które jej używają, zmieniają się razem. Suwaki (`type="range"`) zgłaszają zdarzenie `input` przy każdym ruchu.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Zmienne CSS</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; }

                    :root { --hue: 260; --size: 80; }
                    .tile {
                      display: inline-grid; place-items: center; margin: 0.3em;
                      width: calc(var(--size) * 1px); height: calc(var(--size) * 1px);
                      background: hsl(var(--hue), 70%, 55%); color: white; font-size: 1.5em; border-radius: 8px;
                    }
  </style>
</head>
<body>
  <p><label>Odcień <input id="hue" type="range" min="0" max="360" value="260"></label></p>
  <p><label>Rozmiar <input id="size" type="range" min="40" max="160" value="80"></label></p>
  <div class="tile">A</div><div class="tile">B</div><div class="tile">C</div>
  <script>
    const root = document.documentElement;
    for (const id of ['hue', 'size']) {
      document.getElementById(id).addEventListener('input', e => {
        root.style.setProperty('--' + id, e.target.value);
      });
    }
  </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.