CSS-Stile mit JavaScript auf ein Element anwenden (Tutorial)
![[Bildschirmfoto]
CSS-Stile mit JavaScript auf ein Element anwenden [Bildschirmfoto]
CSS-Stile mit JavaScript auf ein Element anwenden](img/css-stile_mit_javascript_auf_ein_element_anwenden.png)
• Beispiele unter: Image-Highlight (Spotlight) Generator (image-highlight.js)
und Bilder-Farbrotation mit Gradient (im Quelltext)
Inline-Stile
const pizza = document.querySelector('.pizza'); // Ändern der Textfarbe in Tomato (Rot) pizza.style.color = 'Tomato'; // Hintergrundfarbe auf Brown (Braun) setzen pizza.style.backgroundColor = 'Brown'; // Schriftschnitt in kursiv ändern pizza.style.fontStyle = 'italic';
document.getElementById("pizza").style = `color: Tomato; background: Brown;`;
let col = "Tomato"; let backg = "Brown"; document.getElementById("pizza").style = `color: ${col}; background: ${backg};`;
Stile hinzufügen oder entfernen
document.getElementById("pizza").classList.add("Salamie"); document.getElementById("pizza").classList.remove("Thunfisch"); document.getElementById("pizza").classList.toggle("Kaese");
Globale Stile
// Erstellen eines Elements const style = document.createElement('style'); // CSS-Stile hinzufügen style.innerHTML = ` .pizza { color: Tomato; background-color: Brown; font-style: italic; } `; // An dem DOM anhängen document.head.appendChild(style);
CSS-Objektmodell
// Erstellen eines neuen Stils const style = document.createElement('style'); // An dem DOM anhängen document.head.appendChild(style); // CSS-Regel einfügen style.sheet.insertRule(` .pizza { color: Tomato; background-color: Brown; font-style: italic; } `);
Konstruierbare Stylesheets
// Erstellen eines neuen freigegebenen Stylesheets const sheet = new CSSStyleSheet(); // CSS-Stile hinzufügen sheet.replaceSync(` .pizza { color: Tomato; background-color: Brown; font-style: italic; } `); // Anwenden eines Stylesheets auf ein Dokument document.adoptedStyleSheets = [sheet];