Come si aggiunge CSS con Javascript?


154

Come si aggiungono le regole CSS (ad es. strong { color: red }) Utilizzando Javascript?


stessa domanda (risposta è crossbrowser jQuery) stackoverflow.com/a/266110/341744
ninMonkey

18
@monkey: questa è una soluzione piuttosto scadente e in realtà non fa ciò che è stato chiesto qui. es: cosa succede se un nuovo <strong>elemento viene aggiunto al documento.
Nickf

Risposte:


115

Puoi anche farlo utilizzando le interfacce CSS di livello DOM 2 ( MDN ):

var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

... su tutti tranne IE8 (e naturalmente) e precedenti, che utilizza una propria formulazione leggermente diversa:

sheet.addRule('strong', 'color: red;', -1);

C'è un vantaggio teorico in questo rispetto al metodo createElement-set-innerHTML, in quanto non devi preoccuparti di inserire caratteri HTML speciali nell'hMLML interno, ma in pratica gli elementi di stile sono CDATA in HTML legacy e '<' e '&' sono usati raramente nei fogli di stile comunque.

È necessario un foglio di stile in atto prima di poter iniziare ad aggiungerlo in questo modo. Può essere qualsiasi foglio di stile attivo esistente: esterno, incorporato o vuoto, non importa. Se non ce n'è uno, l'unico modo standard per crearlo al momento è con createElement.


"color" .. oh sì, oops! per fortuna quello era solo un esempio. Sospettavo che ci potesse essere un metodo DOM per questo, grazie! +1
nickf

14
il foglio proviene da sheet = window.document.styleSheets[0] (devi avere almeno un <style type = "text / css"> </style>).
AJP,

1
Grazie, tutti gli esempi che Google mostra per primi sono così enormi quando tutto ciò di cui avevo bisogno era di aggiornare la mia memoria su queste due righe.
ElDoRado1239,

1
So che è passato un po 'di tempo, ma quando ho provato il primo, ho ricevutoSecurityError: The operation is insecure.
user10089632

3
@ user10089632 il foglio di stile a cui stai accedendo deve essere offerto dallo stesso host del documento principale affinché funzioni.
Bobince,

225

L'approccio semplice e diretto è quello di creare e aggiungere un nuovo stylenodo al documento.

// Your CSS as text
var styles = `
    .qwebirc-qui .ircwindow div { 
        font-family: Georgia,Cambria,"Times New Roman",Times,serif;
        margin: 26px auto 0 auto;
        max-width: 650px;
    }
    .qwebirc-qui .lines {
        font-size: 18px;
        line-height: 1.58;
        letter-spacing: -.004em;
    }

    .qwebirc-qui .nicklist a {
        margin: 6px;
    }
`

var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)

12
Non dovrebbe essere aggiunto alla testa del documento piuttosto che al corpo?
Bobince

3
@bobince - Secondo le specifiche HTML, assolutamente, ma tutti i browser le riconoscono ovunque. document.bodyè anche più breve da digitare e più veloce da eseguire rispetto a document.getElementsByTagName("head")[0]ed evita i problemi cross-browser di insertRule / addRule.
Ben Blank

4
La soluzione dovrebbe essere seguita da un lungo "duhhhh". Non riesco a credere che non ci abbia pensato.
George Mauer,

8
In tutti i browser recenti puoi semplicemente usare document.head.appendChild.
Gajus

2
Questa soluzione è di gran lunga migliore! Immagina di avere più di un foglio di stile: con la soluzione @bobince il tuo CSS appena aggiunto potrebbe essere sovrascritto dal secondo / terzo / ecc. foglio di stile sulla pagina. Usandoti document.body.appendChild(css);assicurati che il nuovo CSS sia sempre l'ultima regola.
AvL

27

La soluzione di Ben Blank non funzionerebbe in IE8 per me.

Tuttavia, ha funzionato in IE8

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

12
Il buon vecchio IE semplifica sempre la vita
Alex W

2
Si dovrebbe aggiungere l'elemento alla head prima impostazione .cssText, o IE6-8 sarà in crash se il cssCodecontiene un @ -Direttiva, come @importo @font-face, vedere l'aggiornamento a phpied.com/dynamic-script-and-style-elements-in-ie e StackOverflow .com / a / 7952904
Han Seoul-Oh

24

Ecco una versione leggermente aggiornata della soluzione di Chris Herring , tenendo conto che puoi usare innerHTMLanche invece di creare un nuovo nodo di testo:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

3
Si dovrebbe aggiungere l'elemento alla head prima impostazione .cssText, o IE6-8 sarà in crash se il codecontiene un @ -Direttiva, come @importo @font-face, vedere l'aggiornamento a phpied.com/dynamic-script-and-style-elements-in-ie e StackOverflow .com / a / 7952904
Han Seoul-Oh

5

Una fodera più corta

// One liner function:
const addCSS = s =>(d=>{d.head.appendChild(d.createElement("style")).innerHTML=s})(document);

// Usage: 
addCSS("body{ background:red; }")


3

È possibile aggiungere classi o attributi di stile su un elemento in base all'elemento.

Per esempio:

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

Dove puoi fare this.style.background, this.style.font-size, ecc. Puoi anche applicare uno stile usando questo stesso metodo ala

this.className='classname';

Se vuoi farlo in una funzione javascript, puoi usare getElementByID piuttosto che 'this'.


5
JavaScript incorporato utilizzando i gestori di eventi è una pessima idea. Dovresti separare i tuoi contenuti dalle funzionalità e associare i gestori di eventi in JavaScript, preferibilmente in un file esterno.
Colonnello Sponsz,

3

Questo semplice esempio di add <style>in head of html

var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";

document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head

Stile dinamico di origine : manipolazione di CSS con JavaScript


3

YUI ha recentemente aggiunto un'utilità specifica per questo. Vedi stylesheet.js qui.


Attualmente sto usando YUI per il mio lavoro e stavo cercando di capire come modificare fogli di stile esterni di regole CSS esistenti. Non sapevo di questa utility, sembra perfetto! Grazie Russell.
Jaime,

2

Questa è la mia soluzione per aggiungere una regola CSS alla fine dell'ultimo elenco di fogli di stile:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

1

Un'altra opzione è utilizzare JQuery per archiviare la proprietà di stile in linea dell'elemento, aggiungerla ad essa e quindi aggiornare la proprietà di stile dell'elemento con i nuovi valori. Come segue:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

E quindi eseguirlo con i nuovi attributi CSS come oggetto.

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

Questo potrebbe non essere necessariamente il metodo più efficiente (sono aperto a suggerimenti su come migliorarlo. :)), ma sicuramente funziona.


1

Ecco un modello di esempio per aiutarti a iniziare

Richiede 0 librerie e utilizza solo javascript per iniettare sia HTML che CSS.

La funzione è stata presa in prestito dall'utente @Husky sopra

Utile se si desidera eseguire uno script tampermonkey e si desidera aggiungere un overlay di attivazione / disattivazione su un sito Web (ad esempio un'app per le note ad esempio)

// INJECTING THE HTML
document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>';

// CSS INJECTION FUNCTION
///programming/707565/how-do-you-add-css-with-javascript
function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';
    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }
    document.getElementsByTagName("head")[0].appendChild( style );
}

// INJECT THE CSS INTO FUNCTION
// Write the css as you normally would... but treat it as strings and concatenate for multilines
insertCss(
  "#injection {color :red; font-size: 30px;}" +
  "body {background-color: lightblue;}"
)


1

se sai che <style>esiste almeno un tag nella pagina, usa questa funzione:

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

utilizzo:

CSS("div{background:#00F}");

0

Ecco la mia funzione generale che parametrizza il selettore CSS e le regole e opzionalmente accetta un nome file css (sensibile al maiuscolo / minuscolo) se si desidera aggiungere invece a un foglio particolare (altrimenti, se non si fornisce un nome file CSS, creerà un nuovo elemento di stile e lo aggiungerà alla testa esistente. Farà al massimo un nuovo elemento di stile e lo riutilizzerà nelle future chiamate di funzione). Funziona con FF, Chrome e IE9 + (forse anche prima, non testato).

function addCssRules(selector, rules, /*Optional*/ sheetName) {
    // We want the last sheet so that rules are not overridden.
    var styleSheet = document.styleSheets[document.styleSheets.length - 1];
    if (sheetName) {
        for (var i in document.styleSheets) {
            if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                styleSheet = document.styleSheets[i];
                break;
            }
        }
    }
    if (typeof styleSheet === 'undefined' || styleSheet === null) {
        var styleElement = document.createElement("style");
        styleElement.type = "text/css";
        document.head.appendChild(styleElement);
        styleSheet = styleElement.sheet;
    }

    if (styleSheet) {
        if (styleSheet.insertRule)
            styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
        else if (styleSheet.addRule)
            styleSheet.addRule(selector, rules);
    }
}

-1

utilizzare .cssin Jquery come$('strong').css('background','red');

$('strong').css('background','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong> Example
</strong> 


1
javascript, OP non dice nulla su jQuery
agapitocandemor l'
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.