JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

16.6.3 Creating New Stylesheets

16.6.3 Creating New Stylesheets

Finally, it is possible to create entirely new stylesheets and add them to your document. In most browsers, this is done with standard DOM techniques: just create a newelement and insert it into the document head, then use its innerHTML property to set stylesheet content. In IE8 and before, however, a new CSSStyleSheet object is created with the nonstandard method document.createStyleSheet(), and stylesheet text is specified using the cssText property. Example 16-6 demonstrates.

Example 16-6. Creating a new stylesheet

// Add a stylesheet to the document and populate it with the specified styles. // The styles argument can be a string or an object. If it is a string, it // is treated as the text of the stylesheet. If it is an object, then each // property defines a style rule to be added to the stylesheet. Property // names are selectors and their values are the corresponding styles function addStyles(styles) {

// First, create a new stylesheet var styleElt, styleSheet; if (document.createStyleSheet) { // If the IE API is defined, use it

styleSheet = document.createStyleSheet(); } else {

var head = document.getElementsByTagName("head")[0] styleElt = document.createElement("style"); // Newelement head.appendChild(styleElt); // Insert it into

// Now the new stylesheet should be the last one styleSheet = document.styleSheets[document.styleSheets.length-1] }

// Now insert the styles into it

if (typeof styles === "string") { // The argument is stylesheet text if (styleElt) styleElt.innerHTML = styles; else styleSheet.cssText = styles; // The IE API


else { // The argument is an object of individual rules to insert var i = 0; for(selector in styles) {

if (styleSheet.insertRule) { var rule = selector + " {" + styles[selector] + "}"; styleSheet.insertRule(rule, i++);

} else { styleSheet.addRule(selector, styles[selector], i++); } } } }

16.6 Scripting Stylesheets | 443

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1