寫組件時有時想把一些組件特性相關的 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