2011-12-01 11 views
6

Sto sviluppando una pagina Web in cui vorrei aggiungere dinamicamente lo stile da un file javascript esterno.Come aggiungere un tag di stile in una pagina Web da file javascript (js)

Sto usando questo codice che non funziona

this.addStyle = function() 
    { 
     if (! this.inited) { 
      alert("not inited"); 
      return; 
     } 
     var head = document.getElementsByTagName('head')[0], 
     style = document.createElement('style'), 
     rules = document.createTextNode('.bodys { bgcolor="red"; }'); 
     style.type = 'text/css'; 
     if(style.styleSheet) 
      style.styleSheet.cssText = rules.nodeValue; 
     else style.appendChild(rules); 
      head.appendChild(style); 
    } 
+0

Utilizzare la formattazione del codice per la domanda. – cederlof

risposta

1

Change .bodys{ bgcolor="red"; }-.bodys{background-color:red}

1

Non tutti i browser sono applicabili ai nodi di testo generati. MediaWiki utilizza

var s = document.createElement('style'); 
s.type = 'text/css'; 
s.rel = 'stylesheet'; 
if (s.styleSheet) { 
    s.styleSheet.cssText = text; // IE 
} else { 
    s.appendChild(document.createTextNode(text + '')); // Safari sometimes borks on null 
} 

Naturalmente seguire anche la risposta alberts.

+0

Non sono sicuro che davvero 's.rel = 'stylesheet';' sia necessario. – Bergi

Problemi correlati