Agregar reglas a hojas de estilo con JavaScript -

Actualización: Se realizaron reescrituras para representar con precisión la práctica actual para la inyección de hojas de estilo.

Dado que actualmente utilizamos tanto JavaScript en nuestras aplicaciones web, buscamos más formas de mantenerlas rápidas. Usamosla delegación de eventos para mantener la escucha de eventos eficiente, usamosla función antirrebote para limitar el número de veces que se puede usar un método determinado, usamoscargadores de JavaScript para cargar solo los recursos que necesitamos, etc. Otra forma en que podemos hacer que nuestros las páginas sean eficientes y rápidas es agregar y eliminar estilos dinámicamente directamente en una hoja de estilos en lugar de consultar constantemente el DOM en busca de elementos y aplicar estilos. ¡Así es como funciona!

Índice de contenidos
  1. Obtener la hoja de estilo
  2. Crear una nueva hoja de estilo
  3. Inserting Rules
  4. Adding Rules – Nonstandard addRule
  5. Safely Applying Rules
  6. Insertar reglas para consultas de medios

Obtener la hoja de estilo

La hoja de estilo a la que agregas las reglas depende de ti. Si tiene una hoja de estilo específica en mente, puede agregar un IDelemento LINKo STYLEdentro del HTML de su página y obtener el CSSStyleSheetobjeto haciendo referencia a la sheetpropiedad del elemento. Las hojas de estilo se pueden encontrar en el document.styleSheetsobjeto:

var hojas = document.styleSheets; // devuelve una StyleSheetList similar a una matriz/*Returns: StyleSheetList {0: CSSStyleSheet, 1: CSSStyleSheet, 2: CSSStyleSheet, 3: CSSStyleSheet, 4: CSSStyleSheet, 5: CSSStyleSheet, 6: CSSStyleSheet, 7: CSSStyleSheet, 8: CSSStyleSheet , 9: CSSStyleSheet, 10: CSSStyleSheet, 11: CSSStyleSheet, 12: CSSStyleSheet, 13: CSSStyleSheet, 14: CSSStyleSheet, 15: CSSStyleSheet, longitud: 16, elemento: función}*/// Tome la primera hoja, independientemente de la hoja mediavar = documento.styleSheets[0];

Una consideración importante es mediala hoja de estilo: desea asegurarse de no agregar reglas a una hoja de estilo impresa cuando espera que los estilos se muestren en la pantalla. Un CSSStyleSheetobjeto tiene propiedades informativas que usted puede leer detenidamente:

// Obtener información sobre la primera hoja de estiloconsole.log(document.styleSheets[0]);/*Returns: CSSStyleSheetcssRules: CSSRuleListdisabled: falsehref: "https://davidwalsh.name/somesheet.css"media: MediaListownerNode: linkownerRule: nullparentStyleSheet: nullrules: CSSRuleListtitle: nulltype: "text/css"*/// Obtenga el tipo de medioconsole.log(document.styleSheets[0].media.mediaText)/*Returns:"all" o "print" o el medio que se utiliza para esta hoja de estilo*/

En cualquier caso, hay muchas maneras de tomar una hoja de estilo para adjuntarle reglas de estilo.

Crear una nueva hoja de estilo

En muchos casos, puede que sea mejor crear un nuevo STYLEelemento para sus reglas dinámicas. Esto es bastante fácil:

var sheet = (function() {// Create the style tagvar style = document.createElement("style");// Add a media (and/or media query) here if you'd like!// style.setAttribute("media", "screen")// style.setAttribute("media", "only screen and (max-width : 1024px)")// WebKit hack :(style.appendChild(document.createTextNode(""));// Add the style element to the pagedocument.head.appendChild(style);return style.sheet;})();

Unfortunately WebKit requires a hack to properly get things going but all we care about is having that sheet.

Inserting Rules

Stylesheets have an insertRule method which isn’t available in earlier IE’s but is now the standard for rule injection. The insertRule requires that you write the entire CSS rule just as you would in a stylesheet:

sheet.insertRule("header { float: left; opacity: 0.8; }", 1);

This method may seem a bit ugly for a JavaScript API but that’s how it works. The second argument, the index, represents the index at which to insert the rule. This is helpful so that you can insert the same rule/code and define which wins out. The default for index is -1, which means the end of the collection. For extra/lazy control, you may add !important to rules to avoid problems with the index.

Adding Rules – Nonstandard addRule

CSSStyleSheet objects have an addRule method which allows you to register CSS rules within the stylesheet. The addRule method accepts three arguments: the selector, the second the CSS code for the rule, and the third is the zero-based integer index representing the style position (in relation to styles of the same selector):

sheet.addRule("#myList li", "float: left; background: red !important;", 1);

addRule calls return a result of -1 in all cases — it really doesn’t represent anything.

Remember that the advantage here is that elements added from the page automatically have the styles applied to them; i.e. you wont have to add them to elements as they’re injected into the page. Efficient!

Safely Applying Rules

Since browser support for insertRule isn’t as global, it’s best to create a wrapping function to do the rule application. Here’s a quick and dirty method:

function addCSSRule(sheet, selector, rules, index) {if("insertRule" in sheet) {sheet.insertRule(selector + "{" + rules + "}", index);}else if("addRule" in sheet) {sheet.addRule(selector, rules, index);}}// Use it!addCSSRule(document.styleSheets[0], "header", "float: left");

This utility method should cover all cases of new style application. If you are nervous about applying variable styles across your app, it’s reasonable to wrap the inner code of this method in a try{}catch(e){} block.

Insertar reglas para consultas de medios

Las reglas específicas de consultas de medios se pueden agregar de dos maneras. La primera forma es a través del insertRulemétodo estándar:

Sheet.insertRule("@pantalla solo multimedia y (ancho máximo: 1140px) {encabezado {mostrar: ninguno; } }");

Por supuesto, dado que IE no siempre ha sido compatible con insertRule, el otro método es crear un STYLEelemento con el atributo multimedia adecuado y luego agregar estilos a esa nueva hoja de estilos. Esto puede requerir hacer malabarismos con varios STYLEelementos, pero es bastante fácil. probablemente crearía un objeto con consultas de medios como índices y los crearía/recuperaría de esa manera.

Agregar reglas dinámicamente a las hojas de estilo es eficiente y más fácil de lo que piensas. Tenga en cuenta esta estrategia en su próxima gran aplicación, ya que puede ahorrarle trabajo tanto en el código como en el procesamiento de elementos.

Te podría interesar...

Deja una respuesta

Subir