Come si aggiungono le regole CSS (ad es. strong { color: red }) Utilizzando Javascript?
<strong>elemento viene aggiunto al documento.
Come si aggiungono le regole CSS (ad es. strong { color: red }) Utilizzando Javascript?
<strong>elemento viene aggiunto al documento.
Risposte:
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.
sheet = window.document.styleSheets[0] (devi avere almeno un <style type = "text / css"> </style>).
SecurityError: The operation is insecure.
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)
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.
document.head.appendChild.
document.body.appendChild(css);assicurati che il nuovo CSS sia sempre l'ultima regola.
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);
}
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
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 );
}
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
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; }")
È 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'.
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
YUI ha recentemente aggiunto un'utilità specifica per questo. Vedi stylesheet.js qui.
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 }");
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.
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;}"
)
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}");
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);
}
}
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>