Typically, we define CSS in an external stylesheet and then use it.
In previous project, I am required to change the rules defined in CSS dynamically. We normally add or remove rules most of the time and seldom change them. In this case, we should use CSS Rule to deal with it.
CSS Rule Object provide the ability to access and modify rules defined in CSS.
Since IE and Firefox have different implementation, we first look at how to use it:
Browser | Usage |
---|---|
Internet Explorer | document.styleSheets[0].rules[0] |
Firefox | document.styleSheets[0].cssRules[0] |
Let's modify a CSS Rule to see how powerful it is.
For example, we have one stylesheet imported and the content is shown below:
p{ font-size:10px; } |
You want to change this rule so that content inside tag will be in font-size:12px. Here's the code:
var cssSheet=document.styleSheets[0]; var rule=cssSheet.cssRules? mysheet.cssRules[0]: cssSheet.rules[0]; // check compatibility between IE and Firefox rule.style.fontSize="12px"; //remember in javascript we have to use fontSize instead |
This is all the code and it is very simple. We still have a better solution in this case. It is the use of Javascript Framework. I personally recommend you to use JQuery.
Here is where you can find JQuery:
http://jquery.com/
I'll talk about it later.
Reference:
No comments:
Post a Comment