Adding CSS style rules dynamically using JavaScript

Source: Internet
Author: User

Original link: Add Rules to stylesheets with JavaScript
Original Date: 2014-09-04
Translation Date: 2014-09-05
Translators: Anchor

Now there's a lot of JavaScript code in the Web app, and we've been looking for solutions that make them faster.
    • We use event delegation to make event monitoring more efficient,
    • We use function debouncing to limit the number of times a given method is invoked over a period of time, please refer to: How to prevent high frequency triggering of event functions (Chinese translation)
    • We use the JavaScript loader to load the part of the resource that we really need, and so on.
There is also a way to make our pages faster and more efficient. That is, you can dynamically add and remove certain styles from a style sheet by using JS, instead of constantly querying DOM elements and applying various styles. Here's how it works.

Get style sheet

You can add style rules by selecting any style sheet. If you have a certain style sheet, you can give it in the HTML page <link>Or <style>Label add IDproperty, and then directly through the DOM element's sheetproperty to get CssstylesheetObject. Style sheets can also be document.stylesheetsTraverse to:
Returns an array-like (array-like) style list Stylesheetlistvar sheets = document.stylesheets; /* The return value is similar to the following:  stylesheetlist {    0:cssstylesheet,    1:cssstylesheet,    2:cssstylesheet,    3: Cssstylesheet,    4:cssstylesheet,    length:5,    item:function}*///Gets the first sheet, regardless of the media attribute var sheet = Document.stylesheets[0];
Special attention is paid to the style sheet's MediaProperties-When you want to display on the screen, you must not add CSS rules to the plot style sheet. You can take a closer look CssstylesheetProperty information for the object:
Console output information for the first style sheet console.log (document.stylesheets[0]);/* return value:  cssstylesheet    cssrules:cssrulelist[Object]    disabled:false    href: "Http://davidwalsh.name/somesheet.css"    media:medialist[Object]    Ownernode:link [Object]    Ownerrule:null    parentstylesheet:null    rules:cssrulelist[Object]    title:null    type: "Text/css" */// The Get Media type (media type) Console.log (document.stylesheets[0].media.mediatext)/* Return value may be:    "All" or "print" or other media*/that are applied to this style sheet
In all cases, you must have a way to get to the style sheet that you want to add the rule to.

Create a new style sheet

In many cases, the best approach might be to create a new <style> element to hold these dynamic rules. This is also very simple:
var sheet = (function () {    //create <style> tag    var style = document.createelement ("style");    You can add a media (/media query, media query) property    //Style.setattribute ("Media", "screen")    //Style.setattribute ("Media", " Only screens and (max-width:1024px))    //to WebKit hack:(    style.appendchild (document.createTextNode (""));    Add the <style> element to the page    Document.head.appendChild (style);    return style.sheet;}) ();
The tragedy is WebKitNeed a little hackmeans to be created correctly, but we just need to care about this sheet

Insert Rule

In earlier versions of IE stylesheetsOf Insertrulemethod is not available, although this is now the standard for rule injection. Insertrulemethod requires the entire CSS rule to be written, and is the same as in the style sheet:
Sheet.insertrule ("header {float:left; opacity:0.8; } ", 1);
Although this JavaScript API method looks a bit earthy, it does. The second parameter, index, represents the position (index) where the rule is to be inserted. This is also very useful, so that you can insert the same rules/code, which allows the post-rule to take effect. The default index is-1, which represents the end of the entire collection. If you want to have extra/lazy control rules, you can also add!important tags to a rule to avoid problems with indexing.

Add Rule-Non-standard AddRuleMethod

CssstylesheetObject has a AddRuleMethod that allows you to register CSS rules in the style sheet. AddRuleThe method accepts three parameters: the first parameter is the selector (selector), the second parameter is the CSS rule code, and the third is an integer index starting at 0, representing the position of the style (in the same selector):
Sheet.addrule ("#myList li", "FLOAT:LEFT; Background:red!important; ", 1);
AddRuleThe return value of the method is always -1, so this value has no practical significance.
Remember, the advantage of this approach is that the elements added from the page automatically have the styles applied to them, meaning you don't have to add them to the specific elements, but instead inject them directly into the page. Of course more efficient!

Security Application Rules

Because not all browsers support Insertrulemethod, it is best to create a wrapper function to handle the rule application. Here is a quick method of soil:
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);}    } Mode of Use Addcssrule (Document.stylesheets[0], "header", "Float:left");
This tool method should cover all the circumstances of the new style rule. If you are concerned about an error in your application, you should use the code of the method with a try{} catch (e) {}Blocks to pack up.

inserting media query rules

There are two ways to add media query rules. The first is the use of standard InsertruleMethod:
Sheet.insertrule (  "@media only screen and (max-width:1140px) {header {display:none;}}"  );

Of course, because the old version of IE does not support Insertrule, so another way is to create a STYLEelement, and specify the appropriate Mediaproperty, and then add the style to the new style sheet. This may require the use of multiple STYLEelement, but it is also very easy. I might create an object that specifies media queries as well as indexes, and then creates/gets them.

Adding rules to stylesheets dynamically is a highly efficient tool, and may be simpler than you might think. Keep in mind that this scenario may need to be used in your next big application because it prevents you from falling into a hole in both code and element handling.

Adding CSS style rules dynamically using JavaScript

Related Article

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.