How do you add CSS rules (eg strong { color: red }
) by use of Javascript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
This is my solution to add a css rule at the end of the last style sheet list:
The simple-and-direct approach is to create and add a new
style
node to the document.The solution by Ben Blank wouldn't work in IE8 for me.
However this did work in IE8
You can add classes or style attributes on an element by element basis.
For example:
Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala
If you want to do this in a javascript function, you can use getElementByID rather than 'this'.
Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:
And then execute it with the new CSS attributes as an object.
This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.
YUI just recently added a utility specifically for this. See stylesheet.js here.