una propiedades por otra div con clase cambiar agregar javascript css stylesheet

javascript - propiedades - getelementsbyclassname



¿Cómo crear dinámicamente la clase CSS en JavaScript y aplicar? (13)

Utilizando el cierre de google:

puedes usar el módulo ccsom:

goog.require(''goog.cssom''); var css_node = goog.cssom.addCssText(''.cssClass { color: #F00; }'');

El código javascript intenta ser un navegador cruzado al colocar el nodo css en el encabezado del documento.

Necesito crear dinámicamente una clase de hoja de estilo CSS en JavaScript y asignarla a algunos elementos HTML como: div, table, span, tr, etc. y a algunos controles como asp: Textbox, Dropdownlist y datalist.

¿Es posible?

Estaría bien con una muestra.


A partir de IE 9. Ahora puede cargar un archivo de texto y establecer una propiedad style.innerHTML. Básicamente, ahora puede cargar un archivo css a través de ajax (y obtener la devolución de llamada) y luego simplemente configurar el texto dentro de una etiqueta de estilo como esta.

Esto funciona en otros navegadores, no estoy seguro de cuán atrás. Pero siempre y cuando no necesites soportar IE8, entonces funcionará.

// RESULT: doesn''t work in IE8 and below. Works in IE9 and other browsers. $(document).ready(function() { // we want to load the css as a text file and append it with a style. $.ajax({ url:''myCss.css'', success: function(result) { var s = document.createElement(''style''); s.setAttribute(''type'', ''text/css''); s.innerHTML = result; document.getElementsByTagName("head")[0].appendChild(s); }, fail: function() { alert(''fail''); } }) });

y luego puede hacer que tire de un archivo externo como myCss.css

.myClass { background:#F00; }


Aquí está la solución de Vishwanath ligeramente reescrita con comentarios:

function setStyle(cssRules, aSelector, aStyle){ for(var i = 0; i < cssRules.length; i++) { if(cssRules[i].selectorText && cssRules[i].selectorText.toLowerCase() == aSelector.toLowerCase()) { cssRules[i].style.cssText = aStyle; return true; } } return false; } function createCSSSelector(selector, style) { var doc = document; var allSS = doc.styleSheets; if(!allSS) return; var headElts = doc.getElementsByTagName("head"); if(!headElts.length) return; var styleSheet, media, iSS = allSS.length; // scope is global in a function /* 1. search for media == "screen" */ while(iSS){ --iSS; if(allSS[iSS].disabled) continue; /* dont take into account the disabled stylesheets */ media = allSS[iSS].media; if(typeof media == "object") media = media.mediaText; if(media == "" || media==''all'' || media.indexOf("screen") != -1){ styleSheet = allSS[iSS]; iSS = -1; // indication that media=="screen" was found (if not, then iSS==0) break; } } /* 2. if not found, create one */ if(iSS != -1) { var styleSheetElement = doc.createElement("style"); styleSheetElement.type = "text/css"; headElts[0].appendChild(styleSheetElement); styleSheet = doc.styleSheets[allSS.length]; /* take the new stylesheet to add the selector and the style */ } /* 3. add the selector and style */ switch (typeof styleSheet.media) { case "string": if(!setStyle(styleSheet.rules, selector, style)); styleSheet.addRule(selector, style); break; case "object": if(!setStyle(styleSheet.cssRules, selector, style)); styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length); break; }


Aunque no estoy seguro de por qué quieres crear clases CSS con JavaScript, aquí hay una opción:

var style = document.createElement(''style''); style.type = ''text/css''; style.innerHTML = ''.cssClass { color: #F00; }''; document.getElementsByTagName(''head'')[0].appendChild(style); document.getElementById(''someElementId'').className = ''cssClass'';


Encontré una mejor solución, que funciona en todos los navegadores.
Utiliza document.styleSheet para agregar o reemplazar reglas. La respuesta aceptada es breve y práctica, pero esto funciona en IE8 y menos también.

function createCSSSelector (selector, style) { if (!document.styleSheets) return; if (document.getElementsByTagName(''head'').length == 0) return; var styleSheet,mediaType; if (document.styleSheets.length > 0) { for (var i = 0, l = document.styleSheets.length; i < l; i++) { if (document.styleSheets[i].disabled) continue; var media = document.styleSheets[i].media; mediaType = typeof media; if (mediaType === ''string'') { if (media === '''' || (media.indexOf(''screen'') !== -1)) { styleSheet = document.styleSheets[i]; } } else if (mediaType==''object'') { if (media.mediaText === '''' || (media.mediaText.indexOf(''screen'') !== -1)) { styleSheet = document.styleSheets[i]; } } if (typeof styleSheet !== ''undefined'') break; } } if (typeof styleSheet === ''undefined'') { var styleSheetElement = document.createElement(''style''); styleSheetElement.type = ''text/css''; document.getElementsByTagName(''head'')[0].appendChild(styleSheetElement); for (i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].disabled) { continue; } styleSheet = document.styleSheets[i]; } mediaType = typeof styleSheet.media; } if (mediaType === ''string'') { for (var i = 0, l = styleSheet.rules.length; i < l; i++) { if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) { styleSheet.rules[i].style.cssText = style; return; } } styleSheet.addRule(selector,style); } else if (mediaType === ''object'') { var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0; for (var i = 0; i < styleSheetLength; i++) { if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) { styleSheet.cssRules[i].style.cssText = style; return; } } styleSheet.insertRule(selector + ''{'' + style + ''}'', styleSheetLength); } }

La función se utiliza de la siguiente manera.

createCSSSelector(''.mycssclass'', ''display:none'');

Tenga en cuenta que aunque el nombre de la función es createClass, en realidad crea un selector. Así que no olvides agregar. (Punto) antes del nombre de tu clase. No es necesario mencionar que también puede crear otros selectores con esta función.


Hay un complemento ligero de jQuery que permite generar declaraciones de CSS: jQuery-injectCSS

De hecho, utiliza JSS (CSS descrito por JSON), pero es bastante fácil de manejar para generar hojas de estilo css dinámicas.

$.injectCSS({ "#test": { height: 123 } });


Para el beneficio de los buscadores; Si está utilizando jQuery, puede hacer lo siguiente:

var currentOverride = $(''#customoverridestyles''); if (currentOverride) { currentOverride.remove(); } $(''body'').append("<style id=/"customoverridestyles/">body{background-color:pink;}</style>");

Obviamente puedes cambiar el css interno a lo que quieras.

Apreciar a algunas personas que prefieren JavaScript puro, pero funciona y ha sido bastante robusto para escribir / sobrescribir dinámicamente los estilos.


Respuesta corta, esto es compatible "en todos los navegadores" (específicamente, IE8 / 7):

function createClass(name,rules){ var style = document.createElement(''style''); style.type = ''text/css''; document.getElementsByTagName(''head'')[0].appendChild(style); if(!(style.sheet||{}).insertRule) (style.styleSheet || style.sheet).addRule(name, rules); else style.sheet.insertRule(name+"{"+rules+"}",0); } createClass(''.whatever'',"background-color: green;");

Y este bit final aplica la clase a un elemento:

function applyClass(name,element,doRemove){ if(typeof element.valueOf() == "string"){ element = document.getElementById(element); } if(!element) return; if(doRemove){ element.className = element.className.replace(new RegExp("//b" + name + "//b","g")); }else{ element.className = element.className + " " + name; } }

Aquí también hay una pequeña página de prueba: https://gist.github.com/shadybones/9816763

La clave es el hecho de que los elementos de estilo tienen una propiedad "styleSheet" / "sheet" que puede utilizar para agregar / eliminar reglas.


Revisó las respuestas y falta lo más obvio y directo: use document.write() para escribir un trozo de CSS que necesita.

Aquí hay un ejemplo (véalo en codepen: http://codepen.io/ssh33/pen/zGjWga ):

<style> @import url(http://fonts.googleapis.com/css?family=Open+Sans:800); .d, body{ font: 3vw ''Open Sans''; padding-top: 1em; } .d { text-align: center; background: #aaf; margin: auto; color: #fff; overflow: hidden; width: 12em; height: 5em; } </style> <script> function w(s){document.write(s)} w("<style>.long-shadow { text-shadow: "); for(var i=0; i<449; i++) { if(i!= 0) w(","); w(i+"px "+i+"px #444"); } w(";}</style>"); </script> <div class="d"> <div class="long-shadow">Long Shadow<br> Short Code</div> </div>


Un proyecto interesante que podría ayudarlo en su tarea es JSS .

JSS es una mejor abstracción sobre CSS. Utiliza JavaScript como lenguaje para describir estilos de forma declarativa y mantenible. Es un compilador de JS a CSS de alto rendimiento que funciona en tiempo de ejecución en los navegadores y en el lado del servidor.

La biblioteca JSS le permite inyectar en la sección DOM / head usando la función .attach() .

Repl versión en linea para evaluacion.

Más información sobre JSS .

Un ejemplo:

// Use plugins. jss.use(camelCase()) // Create your style. const style = { myButton: { color: ''green'' } } // Compile styles, apply plugins. const sheet = jss.createStyleSheet(style) // If you want to render on the client, insert it into DOM. sheet.attach()


YUI tiene, con mucho, la mejor utilidad de hojas de estilo que he visto por ahí. Te animo a que lo eches un vistazo, pero aquí hay una muestra:

// style element or locally sourced link element var sheet = YAHOO.util.StyleSheet(YAHOO.util.Selector.query(''style'',null,true)); sheet = YAHOO.util.StyleSheet(YAHOO.util.Dom.get(''local'')); // OR the id of a style element or locally sourced link element sheet = YAHOO.util.StyleSheet(''local''); // OR string of css text var css = ".moduleX .alert { background: #fcc; font-weight: bold; } " + ".moduleX .warn { background: #eec; } " + ".hide_messages .moduleX .alert, " + ".hide_messages .moduleX .warn { display: none; }"; sheet = new YAHOO.util.StyleSheet(css);

Obviamente, existen otras formas mucho más sencillas de cambiar los estilos sobre la marcha, como las que se sugieren aquí. Si tienen sentido para su problema, podrían ser los mejores, pero definitivamente hay razones por las que modificar css es una mejor solución. El caso más obvio es cuando necesita modificar una gran cantidad de elementos. El otro caso importante es si necesita que los cambios de estilo involucren a la cascada. Usar el dom para modificar un elemento siempre tendrá una prioridad más alta. Es el enfoque de martillo y es equivalente a usar el atributo de estilo directamente en el elemento html. Ese no es siempre el efecto deseado.


https://jsfiddle.net/xk6Ut/256/

Una opción para crear y actualizar dinámicamente la clase CSS en JavaScript:

  • Usando el elemento de estilo para crear una sección de CSS
  • Usando una identificación para el elemento de estilo para que podamos actualizar el CSS
    clase

.....

function writeStyles(styleName, cssText) { var styleElement = document.getElementById(styleName); if (styleElement) document.getElementsByTagName(''head'')[0].removeChild( styleElement); styleElement = document.createElement(''style''); styleElement.type = ''text/css''; styleElement.id = styleName; styleElement.innerHTML = cssText; document.getElementsByTagName(''head'')[0].appendChild(styleElement); }

...

var cssText = ''.testDIV{ height:'' + height + ''px !important; }''; writeStyles(''styles_js'', cssText)


function createCSSClass(selector, style, hoverstyle) { if (!document.styleSheets) { return; } if (document.getElementsByTagName("head").length == 0) { return; } var stylesheet; var mediaType; if (document.styleSheets.length > 0) { for (i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].disabled) { continue; } var media = document.styleSheets[i].media; mediaType = typeof media; if (mediaType == "string") { if (media == "" || (media.indexOf("screen") != -1)) { styleSheet = document.styleSheets[i]; } } else if (mediaType == "object") { if (media.mediaText == "" || (media.mediaText.indexOf("screen") != -1)) { styleSheet = document.styleSheets[i]; } } if (typeof styleSheet != "undefined") { break; } } } if (typeof styleSheet == "undefined") { var styleSheetElement = document.createElement("style"); styleSheetElement.type = "text/css"; document.getElementsByTagName("head")[0].appendChild(styleSheetElement); for (i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].disabled) { continue; } styleSheet = document.styleSheets[i]; } var media = styleSheet.media; mediaType = typeof media; } if (mediaType == "string") { for (i = 0; i < styleSheet.rules.length; i++) { if (styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase()) { styleSheet.rules[i].style.cssText = style; return; } } styleSheet.addRule(selector, style); } else if (mediaType == "object") { for (i = 0; i < styleSheet.cssRules.length; i++) { if (styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) { styleSheet.cssRules[i].style.cssText = style; return; } } if (hoverstyle != null) { styleSheet.insertRule(selector + "{" + style + "}", 0); styleSheet.insertRule(selector + ":hover{" + hoverstyle + "}", 1); } else { styleSheet.insertRule(selector + "{" + style + "}", 0); } } } createCSSClass(".modalPopup .header", " background-color: " + lightest + ";" + "height: 10%;" + "color: White;" + "line-height: 30px;" + "text-align: center;" + " width: 100%;" + "font-weight: bold; ", null);