写组件时有时想把一些组件特性相关的 CSS 样式封装在 JS 里,这样更内聚,改起来方便。JS 动态插入 CSS 两个步骤就能够javascript
先看下 document.styleSheets,随意打开一个页面css
其中前三个是经过 link 标签引入的 CSS 文件,第四个是经过 style 标签内联在页面里的 CSS。有以下属性html
每个 cssRule 又有以下属性java
其中的 cssText 正是写在 style 的源码。git
首先,须要建立一个 style 对象,返回其 stylesheet 对象github
/* * 建立一个 style, 返回其 stylesheet 对象 * 注意:IE6/7/8中使用 style.stylesheet,其它浏览器 style.sheet */ function createStyleSheet() { var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; head.appendChild(style); return style.sheet ||style.styleSheet; }
添加函数 addCssRule 以下浏览器
/* * 动态添加 CSS 样式 * @param selector {string} 选择器 * @param rules {string} CSS样式规则 * @param index {number} 插入规则的位置, 靠后的规则会覆盖靠前的 */ function addCssRule(selector, rules, index) { index = index || 0; if (sheet.insertRule) { sheet.insertRule(selector + "{" + rules + "}", index); } else if (sheet.addRule) { sheet.addRule(selector, rules, index); } }
须要注意,标准浏览器支持 insertRule, IE低版本则支持 addRule。app
完整代码以下函数
/* * 动态添加 CSS 样式 * @param selector {string} 选择器 * @param rules {string} CSS样式规则 * @param index {number} 插入规则的位置, 靠后的规则会覆盖靠前的 */ var addCssRule = function() { // 建立一个 style, 返回其 stylesheet 对象 // 注意:IE6/7/8中使用 style.stylesheet,其它浏览器 style.sheet function createStyleSheet() { var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; head.appendChild(style); return style.sheet ||style.styleSheet; } // 建立 stylesheet 对象 var sheet = createStyleSheet(); // 返回接口函数 return function(selector, rules, index) { index = index || 0; if (sheet.insertRule) { sheet.insertRule(selector + "{" + rules + "}", index); } else if (sheet.addRule) { sheet.addRule(selector, rules, index); } } }();
若是只支持移动端或现代浏览器,能够去掉低版本IE判断的代码htm
/* * 动态添加 CSS 样式 * @param selector {string} 选择器 * @param rules {string} CSS样式规则 * @param index {number} 插入规则的位置, 靠后的规则会覆盖靠前的,默认在后面插入 */ var addCssRule = function() { // 建立一个 style, 返回其 stylesheet 对象 function createStyleSheet() { var style = document.createElement('style'); style.type = 'text/css'; document.head.appendChild(style); return style.sheet; } // 建立 stylesheet 对象 var sheet = createStyleSheet(); // 返回接口函数 return function(selector, rules, index) { index = index || 0; sheet.insertRule(selector + "{" + rules + "}", index); } }();
在线DEMO:http://snandy.github.io/lib/func/addCssRule.html
相关:
https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule