如何使用Javascript添加CSS?
如何使用Javascript添加CSS规则(例如 strong {color:red}
)?
How do you add CSS rules (eg strong { color: red }
) by use of Javascript?
也可以使用DOM Level 2 CSS接口:
You can also do this using DOM Level 2 CSS interfaces:
var sheet = window.document.styleSheets[0]
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
...除了(自然)IE,它使用自己的边缘不同的措辞: / p>
...on all but (naturally) IE, which uses its own marginally-different wording:
sheet.addRule('strong', 'color: red;', -1);
这与createElement-set-innerHTML方法相比有一个理论上的优势,不必担心在innerHTML中放置特殊的HTML字符,但在实践中,样式元素是旧式HTML中的CDATA,而且<'和'&'很少用于样式表。
There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.
你需要一个样式表,然后才能像这样开始附加。这可以是任何现有的活动样式表:外部,嵌入或空,这没关系。如果没有一个,目前唯一标准的创建方式是使用createElement。
You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.