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 interface description of IE is more discussed. Program But logically, FF is more reasonable.
I provide two methods similar to IE Code Simple packaging, but ie cannot guarantee that the rules will be synced after Dom CSS removerule. 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.
Copy code The Code is as follows: <style>
#:
{
Color: blue;
}
</Style>
<Style>
#:
{
Background: Gray;
}
</Style>
<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>
<Div id = "A">
ABC
</Div>
<Button onclick = 'addcssrule ("# A", "color: red; Background: yellow;") '>
Add </button>
<Button onclick = 'removecssrule ("# A") '>
Remove </button>
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.