[JavaScript] Add CSS rule using JavaScript

Source: Internet
Author: User

Come to hang a week, harvest a lot, grow a lot.

Saturday in a plug-in when encountered the need to dynamically add pseudo-elements of the demand, searched the solution, someone used the regular to write the read pseudo-elements of the function; I think it is possible to inject CSS rule to allow the reservation of certain classes of tags dynamically generated pseudo-elements.

And then on Google to search for such an article, said the previous not understand the API functions: Addrule, translation, share a bit.

Original post URL: http://davidwalsh.name/add-rules-stylesheets

The translation is as follows:

Because we are using more and more JavaScript in development, we always try to make it faster. We use event proxies to listen for events, use function throttling to limit the number of calls to functions per unit time, and use the loader method to load the most needed resources. These methods can make our page loading, rendering, execution speed to a certain speed. This article is about another way to apply some styles by dynamically adding and removing CSS styles instead of the original find nodes and modifying them.

    • Get style sheet

We can choose to add a style to a stylesheet in the page. You can add an ID to a <link> tag or <style> tag to get the Cssstylesheet object by referencing the sheet property of the node. The stylesheets in the page can be obtained using document.stylesheets:

varSheets =document.stylesheets;//returns an array-like stylesheetlist//returns an array of class objects/*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:cssstyleshe ET, 12:cssstylesheet, 13:cssstylesheet, 14:cssstylesheet, 15:cssstylesheet, Length:16, item:function}*///Grab The first sheet, regardless of media//regardless of the first style of the specific application media (note: May be print, etc.)varSheet = document.stylesheets[0];

When we choose the link or style tag, we should consider whether the selected style sheet tag is applied to screen, not print, and so on. The Cssstylesheet object provides us with such properties:

//Get Info about the first stylesheetConsole.log (document.stylesheets[0]);/*returns:cssstylesheet cssrules:cssrulelist disabled:false href: "Http://davidwalsh.name/somesheet.css"    Media:medialist ownernode:link ownerrule:null parentstylesheet:null rules:cssrulelist title:null Type: "Text/css"*///Get the media type//Get Media typeConsole.log (document.stylesheets[0].media.mediatext)/*Returns: "All" or "print" or whichever media are used for this stylesheet*/

Of course, there are other ways to get the Stylesheet object besides the above.

  

    • Create a new style sheet

In some cases, you might create a new style node to load the newly added style rule. The method is simple:

varSheet = (function() {    //Create the <style> tag    varstyle = 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:(        //webkit kernel browser hack:Style.appendchild (document.createTextNode ("")); //Add The <style> element to the page insert pagesDocument.head.appendChild (style); returnStyle.sheet;})    (); 

Please note that the third statement above is the hack added for the WebKit browser.

  

    • Insert Rule insertrule (Styles,[index])

The StyleSheets object provides insertrule (translator Note: IE8 and the following incompatible, specific reference link http://www.quirksmode.org/dom/w3c_css.html) method. The Insertrule function requires the input of a CSS style-style str as a parameter.

Specific invocation method:

Sheet.insertrule ("header {float:left; opacity:0.8; } ", 1);

(Translator Note: The format of the incoming style STR is very demanding.) As far as I can see: 1. {} Two curly braces and preferably preceded by a space of 2. If it is a webkit kernel, the function throws err when parsing a style rule with a-moz-prefix)

This method looks a little ugly, but it does help. The second argument, index, indicates which of the styles inside the style we will insert into the new CSS rule, which helps us to implement the overwrite of the original style. The default index value is-1 (translator note: But input-1 in Chrome 41 throws the err, the hint parameter can not be less than 0, here is worth studying), indicating that the default is appended to the style. If you want to force overwrite, you can use! Important to avoid the insertion order causing other problems.

    • Add rule (non-standard function) AddRule (Selector,styles,index)

The Cssstylesheet object has a nonstandard function addrule, which, compared to Insertrule, is more like the invocation style of the JS API, without needing to notice the format of the inserted style string itself. The Addrule method accepts three parameters, namely the selector selector, the style string "color:red;font-size:12px", and the Insertion Order index.

Sheet.addrule ("#myList li", "FLOAT:LEFT; Background:red!important; ", 1);

The method has a return value of-1. But there's no specific meaning.

This way you can quickly and efficiently change the existing style of the nodes on the page.

  

    • Apply Styles

Because the above mentioned two functions are not common API functions, it is necessary to do a browser compatibility processing.

function addcssrule (sheet, selector, rules, index) {    if in sheet) {        + "{" + Rules + "}" , index);    }     Else if inch sheet) {        Sheet.addrule (selector, rules, index);    }} // Use it! Addcssrule (Document.stylesheets[0], "header", "Float:left");

This approach can be applied to all advanced browsers, and if you still have concerns, you can use the Try-catch structure when you call.

    • Insert a style rule for media queries

If you need to insert a media-queries CSS style rule, you can only use the first Insertrule method.

Sheet.insertrule ("@media only screen and (max-width:1140px) {header {display:none;}}");

IE does not support the Insertrule function, so another method is to create a style label node that is written to inject style rules.

It is effective and easy to add style rules dynamically. Try it out in the next app and you'll find it's really good to use ~

End of translation

[JavaScript] Add CSS rule 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.