Use JavaScript to create a new style sheet and a new style rule.

Source: Internet
Author: User

Use JavaScript to create a new style sheet and a new style rule.

In today's era, a large amount of JavaScript is widely used on Web pages. We need to find various ways to optimize them to make them faster. We use event delegation to make event listeners more efficient. We use the frequency reduction technology to limit the number of times certain methods are used, and various JavaScript loaders are used to dynamically load the resources we need. Another way to make pages more efficient and agile is to dynamically add or remove styles in the style sheet, without having to query DOM elements and adjust the style of each element. Next let's take a look at how to use this technology!

Capture Style Sheets

You may reference more than one style file on your page. You can select one of them. If you specify an object, you can add an ID to the LINK and STYLE labels on the HTML page to get the CSSStyleSheet object, which is stored in the document. styleSheets object.

Var sheets = document. styleSheets; // returns a StyleSheetList array/* returns: StyleSheetList {0: CSSStyleSheet, 1: external, 2: CSSStyleSheet, 3: CSSStyleSheet, 4: CSSStyleSheet, 5: External, 6: week, 7: CSSStyleSheet, 8: CSSStyleSheet, 9: CSSStyleSheet, 10: Week, 11: Week, 12: CSSStyleSheet, 13: CSSStyleSheet, 14: CSSStyleSheet, 15: CSSStyleSheet, length: 16, item: function} * // find the style table var sheet = document you want to modify. styleSheets [0];

One important thing to note is the media attribute of the style sheet-if you are not careful, when you want to display the style sheet used on the screen for modification, you may mistakenly modify the Style Sheet Used for print. The CSSStyleSheet object contains various attribute information, which you can obtain if needed.

// Get info about the first stylesheetconsole. log (document. styleSheets [0]);/* returned result: CSSStyleSheet cssRules: CSSRuleList disabled: false href: "http://davidwalsh.name/somesheet.css" media: MediaList ownerNode: link ownerRule: null rule: null rules: CSSRuleList title: null type: "text/css" * // Get the media typeconsole. log (document. styleSheets [0]. media. mediaText)/* Returns: "all" or "print" or whichever media is used for this stylesheet */

There are many ways to capture a style sheet and add new style rules to it.

Create a new style sheet

Most of the time, the best way is to create a new STYLE element and dynamically add rules to it. Very simple:

Var sheet = (function () {// Create the <style> tag var style = document. createElement ("style"); // you can add the media attribute (or media query) // style if you want. setAttribute ("media", "screen") // style. setAttribute ("media", "@ media only screen and (max-width: 1024px)") // WebKit patch style. appendChild (document. createTextNode (""); // Add the <style> element to the page document. head. appendChild (style); return style. sheet ;})();

Unfortunately, the WebKit Browser needs to be slightly modified to make the above Code run correctly. However, no matter what, we get the desired sheet.

Add style rules-standard addRule Method

The CSSStyleSheet object contains an addRule method, which can take three parameters: selector, CSS code of the style rule, and an integer. This integer is used to indicate the position of the style table (relative to the same selector):

Sheet. addRule ("# myList li", "float: left; background: red! Important; ", 1 );
The default position is-1, indicating that it is placed at the end. You can add rules for additional control or lazy writing! Important to eliminate location problems. When addRule is called,-1 is returned -- It indicates nothing.

You will find that the advantage of this technology is that it can dynamically add style rules to the page and apply them; you do not have to perform operations on each element, the browser will automatically apply these rules. Efficient!

Add style rules

The CSSStyleSheet object also has an insertRule method, but this method was not available in earlier IE. The insertRule method combines the first two parameters of the addRule method:

Sheet. insertRule ("header {float: left; opacity: 0.8;}", 1 );
This method looks ugly, but is undoubtedly very useful.

Secure Application style rules

Because not all browsers support insertRule, we 'd better encapsulate it to ensure effective code execution. The following is a simple encapsulation method:

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

This method can cope with various situations. If you want to use the code in this method separately, you 'd better use try {} catch (e) {} to pack them.

Add style rules for Media Queries

There are two ways to add style rules for specific media queries. The first is through the standard insertRule method:

Sheet. insertRule ("@ media only screen and (max-width: 1140px) {header {display: none ;}}");
Because the old IE does not support insertRule, we can use another method, that is, to create a STYLE element, assign it the correct media attribute, and then add a new STYLE rule to it. This method adds additional STYLE elements, but it is very simple.

I think it is very efficient and simple to add style rules to the style sheet dynamically. Remember to try this technology in your next application, which saves you a lot of effort.

(English: Add Rules to Stylesheets with JavaScript .)

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.