Javascript code _ javascript

Source: Internet
Author: User
Although jquery supports the css selector, some css rules can be placed in js. js is more flexible than css in any case. But js modifies the stlye of dom htmlelement, which is an operation rather than a rule. When we need a rule, we cannot perform this operation every time the dom changes. Otherwise, it is too inefficient.
Fortunately, css rules in dom can also be modified. However, different browsers have different descriptions of css rules interfaces. in ie, the hash table method is used, while ff is used as an array.
In terms of programmability, the description of the ie interface is more appealing to programmers, but logically, ff is more reasonable.
I provide a method similar to ie for simple packaging of the two sets of Code. However, after the css removeRule of dom, ie cannot guarantee that the rules will be synced. Therefore, it is best to use the rule overwrite method instead of the remove Method.
Note that when using the js function, there must be at least one style label on the page. The following is the code and example.

The Code is as follows:




Script
Function addCSSRule (key, value ){
Var css = document. styleSheets [document. styleSheets. length-1];
Css.css Rules?
(Css. insertRule (key + "{" + value + "}", css.css Rules. length )):
(Css. addRule (key, value ));
}
Function removeCSSRule (key ){
For (var I = 0; I <document. styleSheets. length; I ++ ){
Var css = document. styleSheets [I];
Css.css Rules?
(Function (){
For (var j = 0; j <css.css Rules. length; j ++ ){
If(css.css Rules [j]. selectorText = key ){
Css. deleteRule (j );
}
}
})():
(Css. removeRule (key ));
}
}
Script


Abc



Add

Remove

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.