JS operation CSS to implement code _JAVASCRIPT skills

Source: Internet
Author: User
When we need a rule, we can't do it every time the DOM changes, otherwise it's too inefficient.
The CSS rules in DOM can also be modified. However, different browsers for the CSS rules of the interface description is also different, where IE in the same way as hash table, and FF in array mode.
From the programmability, IE interface description is more pleasing to programmers, but logically, FF is obviously more reasonable.
I have provided a way to simply package two sets of code similar to IE, but after the CSS removerule of the DOM, ie cannot be sure to cash the rules synchronously. So it's best to use rules to cover the way rather than remove.
Note that when you use the Change JS function, the page must have at least one style label. Here's the code and the example.
Copy Code code as follows:

<style>
#a:
{
Color:blue;
}
</style>
<style>
#a:
{
Background:gray;
}
</style>
<script>
function Addcssrule (key,value) {
var css = document.stylesheets[document.stylesheets.length-1];
Css.cssrules?
(Css.insertrule (key+ "{" +value+ "}", Css.cssRules.length)):
(Css.addrule (Key,value));
}
function Removecssrule (key) {
for (var i = 0; i < document.styleSheets.length; i++) {
var css = document.stylesheets[i];
Css.cssrules?
(function () {
for (var j = 0; J < Css.cssRules.length; J + +) {
if (Css.cssrules[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>
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.