modificar llamar lista insertar elementos desde con codigo atributos javascript html css

lista - llamar javascript desde html



Cómo crear una etiqueta<style> con Javascript (12)

Para aquellos que ya están usando jQuery , puedes usar este one-liner:

$(''<style>''+ styles +''</style>'').appendTo(document.head);

Estoy buscando una manera de insertar una etiqueta <style> en una página HTML con JavaScript.

La mejor manera que encontré hasta ahora:

var divNode = document.createElement("div"); divNode.innerHTML = "<br><style>h1 { background: red; }</style>"; document.body.appendChild(divNode);

Esto funciona en Firefox, Opera e Internet Explorer, pero no en Google Chrome. También es un poco feo con el <br> al frente para IE.

¿Alguien sabe de una manera de crear una etiqueta <style> que

  1. Es mejor

  2. Funciona con Chrome?

O tal vez

  1. Esto es una cosa no estándar que debería evitar

  2. Tres navegadores que funcionan son geniales y ¿quién usa Chrome de todos modos?


A menudo hay una necesidad de anular las reglas existentes, por lo que agregar nuevos estilos a la HEAD no funciona en todos los casos.

Se me ocurrió esta sencilla función que resume todas las aproximaciones no válidas "anexas al CUERPO" y es más conveniente de usar y depurar (IE8 +).

window.injectCSS = (function(doc){ // wrapper for all injected styles and temp el to create them var wrap = doc.createElement(''div''); var temp = doc.createElement(''div''); // rules like "a {color: red}" etc. return function (cssRules) { // append wrapper to the body on the first call if (!wrap.id) { wrap.id = ''injected-css''; wrap.style.display = ''none''; doc.body.appendChild(wrap); } // <br> for IE: http://goo.gl/vLY4x7 temp.innerHTML = ''<br><style>''+ cssRules +''</style>''; wrap.appendChild( temp.children[1] ); }; })(document);

Demo: codepen , jsfiddle


Aquí hay un script que agrega los createStyleSheet() y addRule() al estilo de IE a los navegadores que no los tienen:

if(typeof document.createStyleSheet === ''undefined'') { document.createStyleSheet = (function() { function createStyleSheet(href) { if(typeof href !== ''undefined'') { var element = document.createElement(''link''); element.type = ''text/css''; element.rel = ''stylesheet''; element.href = href; } else { var element = document.createElement(''style''); element.type = ''text/css''; } document.getElementsByTagName(''head'')[0].appendChild(element); var sheet = document.styleSheets[document.styleSheets.length - 1]; if(typeof sheet.addRule === ''undefined'') sheet.addRule = addRule; if(typeof sheet.removeRule === ''undefined'') sheet.removeRule = sheet.deleteRule; return sheet; } function addRule(selectorText, cssText, index) { if(typeof index === ''undefined'') index = this.cssRules.length; this.insertRule(selectorText + '' {'' + cssText + ''}'', index); } return createStyleSheet; })(); }

Puede agregar archivos externos a través de

document.createStyleSheet(''foo.css'');

y dinámicamente crear reglas a través de

var sheet = document.createStyleSheet(); sheet.addRule(''h1'', ''background: red;'');


Aquí hay una variante para agregar dinámicamente una clase

function setClassStyle(class_name, css) { var style_sheet = document.createElement(''style''); if (style_sheet) { style_sheet.setAttribute(''type'', ''text/css''); var cstr = ''.'' + class_name + '' {'' + css + ''}''; var rules = document.createTextNode(cstr); if(style_sheet.styleSheet){// IE style_sheet.styleSheet.cssText = rules.nodeValue; } else { style_sheet.appendChild(rules); } var head = document.getElementsByTagName(''head'')[0]; if (head) { head.appendChild(style_sheet); } } }


Esta función inyectará gramaticalmente css siempre que llame a la función appendStyle así: appendstyle(''css you want to inject'') . esto funciona al inyectar un nodo de style en la cabeza del documento. esta es una técnica similar a la que usa la gente para cargar de forma lenta el javascript Funciona consistentemente en la mayoría de los navegadores.

appendStyle = function (content) { style = document.createElement(''style''); style.type = ''text/css''; style.appendChild(document.createTextNode(content)); document.head.appendChild(style); }

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="keywords" content="h, asjkdh, kajhjsdkjh, kjhhgskajhg, vbafd"> <meta name="description" content="hekkliahsmhdasx"> <title>helabahe</title> </head> <body> <h1>this is injected css</h1> <p>heloo, this is stuff, hkasjdhakhd</p> <button onclick=''appendStyle("body {background-color:#ff0000;background-repeat:no-repeat;background-position:top left;background-attachment:fixed;} h1{font-family:Helvetica, sans-serif;font-variant:small-caps;letter-spacing:3px;color:#ff0000;background-color:#000000;} p {font-family:Georgia, serif;font-size:14px;font-style:normal;font-weight:normal;color:#000000;background-color:#ffff00;}")''>press me to inject css!</button> </body> </html>

También puede cargar archivos CSS externos de forma perezosa utilizando el siguiente fragmento de código:

<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />

let linkElement: HTMLLinkElement = this.document.createElement(''link''); linkElement.setAttribute(''rel'', ''stylesheet''); linkElement.setAttribute(''type'', ''text/css''); linkElement.setAttribute(''href'', ''data:text/css;charset=UTF-8,'' + encodeURIComponent(myStringOfstyles));


Esta variable de objeto agregará una etiqueta de estilo a la etiqueta de cabecera con el atributo de tipo y una regla de transición simple dentro que coincida con cada ID / clase / elemento. Siéntase libre de modificar la propiedad del contenido e inyectar tantas reglas como sea necesario. Solo asegúrese de que las reglas de css dentro del contenido permanezcan en una línea (o "escape" cada nueva línea, si así lo prefiere).

var script = { type: ''text/css'', style: document.createElement(''style''), content: "* { transition: all 220ms cubic-bezier(0.390, 0.575, 0.565, 1.000); }", append: function() { this.style.type = this.type; this.style.appendChild(document.createTextNode(this.content)); document.head.appendChild(this.style); }}; script.append();


Intenta agregar el elemento de style a la head lugar del body .

Esto fue probado en IE (7-9), Firefox, Opera y Chrome:

var css = ''h1 { background: red; }'', head = document.head || document.getElementsByTagName(''head'')[0], style = document.createElement(''style''); style.type = ''text/css''; if (style.styleSheet){ // This is required for IE8 and below. style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style);


Si el problema al que te enfrentas es inyectar una cadena de CSS en una página, es más fácil hacerlo con el elemento <link> que con el elemento <style> .

Lo siguiente agrega p { color: green; } p { color: green; } gobernar a la página.

<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />

Puede crear esto en JavaScript simplemente mediante una URL que codifique su cadena de CSS y agregue el atributo HREF . Mucho más simple que todas las peculiaridades de los elementos <style> o acceder directamente a las hojas de estilo.

let linkElement: HTMLLinkElement = this.document.createElement(''link''); linkElement.setAttribute(''rel'', ''stylesheet''); linkElement.setAttribute(''type'', ''text/css''); linkElement.setAttribute(''href'', ''data:text/css;charset=UTF-8,'' + encodeURIComponent(myStringOfstyles));

Esto funcionará en IE 5.5 hacia arriba


Supongo que desea insertar una etiqueta de style en lugar de una etiqueta de link (que hace referencia a un CSS externo), así es como lo hace el siguiente ejemplo:

<html> <head> <title>Example Page</title> </head> <body> <span> This is styled dynamically via JavaScript. </span> </body> <script type="text/javascript"> var styleNode = document.createElement(''style''); styleNode.type = "text/css"; // browser detection (based on prototype.js) if(!!(window.attachEvent && !window.opera)) { styleNode.styleSheet.cssText = ''span { color: rgb(255, 0, 0); }''; } else { var styleText = document.createTextNode(''span { color: rgb(255, 0, 0); } ''); styleNode.appendChild(styleText); } document.getElementsByTagName(''head'')[0].appendChild(styleNode); </script> </html>

Además, noté en tu pregunta que estás usando innerHTML . Esta es en realidad una forma no estándar de insertar datos en una página. La mejor práctica es crear un nodo de texto y agregarlo a otro nodo de elemento.

Con respecto a su pregunta final, escuchará a algunas personas decir que su trabajo debería funcionar en todos los navegadores. Todo depende de tu audiencia. Si nadie en tu audiencia está usando Chrome, entonces no te preocupes; sin embargo, si está buscando llegar a la mayor audiencia posible, es mejor que admita todos los principales navegadores de categoría A



Un ejemplo que funciona y es compatible con todos los navegadores:

var ss = document.createElement("link"); ss.type = "text/css"; ss.rel = "stylesheet"; ss.href = "style.css"; document.getElementsByTagName("head")[0].appendChild(ss);


var list = document.querySelector("head"); list.innerHTML += ''<style> h3.header-6.basket-item--header span.cusplus { color:#c00; }. cusname{ color:grey;font-size:14px; } </style>'';

Código de trabajo del 200%, ejemplo anterior.