Create new style sheets and new style rules _php instances using JavaScript

Source: Internet
Author: User
In this age, the popularity of Web pages using a lot of JavaScript, we need to find a variety of ways to optimize them, make them faster. We use event delegates to make event listeners more efficient, use frequency reduction techniques to limit the number of uses of certain methods, use various JavaScript loaders to dynamically load the resources we need, and so on. Another way to make the page more efficient and agile is to dynamically add or remove styles from the stylesheet without having to query DOM elements and make a style adjustment for each element. Let's take a look at how to use this technology!

Capturing style Sheets

More than one style file may be referenced on your page, and you can choose one of them. If you specify something, you can make a difference by adding an ID to the link and style tag in the HTML page to get the Cssstylesheet object, which is stored in the Document.stylesheets object.

var sheets = document.stylesheets; Returns an Stylesheetlist array/* returned: stylesheetlist {0:cssstylesheet, 1:cssstylesheet, 2:cssstylesheet, 3:cssstylesheet, 4:cs Sstylesheet,5:cssstylesheet, 6:cssstylesheet, 7:cssstylesheet, 8:cssstylesheet, 9:cssstylesheet, 10:cssstylesheet, 1 1:cssstylesheet, 12:cssstylesheet, 13:cssstylesheet, 14:cssstylesheet, 15:cssstylesheet, Length:16, item:function}* Find the style sheet you want to modify var sheet = document.stylesheets[0];

One important thing to be aware of is the media properties of the stylesheet--if you're not careful, you might incorrectly modify the style sheet used for printing (print) When you want to make changes to the style table that you're using on the screen. The Cssstylesheet object has various property information that you can get from it when needed.

Get info about the first stylesheetconsole.log (Document.stylesheets[0]);/* return result: Cssstylesheet cssrules:cssrulelist Disabled:false href: "" Media:medialist ownernode:link ownerrule:null Parentstylesheet:null rules:cssrulelist title:null Type: "Text/css" *///Get the media typeconsole.log (Document.stylesh Eets[0].media.mediatext)/*returns: "All" or "print" or whichever media are used for this stylesheet*/

There are a number of ways you can 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 that dynamically adds rules to it. Very simple:

var sheet = (function () {//Create the <style> tag var style = Document.createelement ("style");  If you want, you can add media properties (or media query)/  /Style.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 type of browser requires a little bit of change to make the above code work correctly, but we get the sheet we want anyway.

Add Style rule – Standard Addrule method

There is a Addrule method in the Cssstylesheet object that accepts 3 parameters: a selector, a CSS code for a style rule, and an integer that indicates the position of the style sheet (relative to the same selector):

Sheet.addrule ("#myList li", "FLOAT:LEFT; Background:red!important; ", 1);
The position default value is-1, which means that it is placed last. For extra control, or lazy writing, you can add!important to the rule to eliminate the problem caused by the position. Calling Addrule will return -1--it does not represent anything.

You'll find that the advantage of this technique is that it dynamically adds style rules to the page and applies them; you don't have to manipulate each element, and the browser automatically applies the rules. It's efficient!

New Style rule

There is a Insertrule method in the Cssstylesheet object, but there is no such method in the early ie. The Insertrule method mixes the first two parameters of the Addrule method together:

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, it's a good idea to do some encapsulation to ensure that the code executes effectively. The following is a very 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 approach can handle a variety of situations. If you want to use the code in this method separately, it's best to wrap them up with Try{}catch (e) {}.

Add style rules for media query (Queries)

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

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

Because old-fashioned IE does not support insertrule, we can use another method, which is to create a style element, give it the correct media properties, and then add a new style rule to it. This approach adds an extra style element, but it's very simple.

I think it's a very efficient and simple technique to add style rules to a style table dynamically. Remember to try this technique in your next app and it will save you a lot of effort.

The above is to use JavaScript to create new style sheets and new style rules _php instance of the content, more relevant content please pay attention to (!

  • 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: 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.