首頁  >  文章  >  web前端  >  JavaScript動態插入CSS的方法_javascript技巧

JavaScript動態插入CSS的方法_javascript技巧

WBOY
WBOY原創
2016-05-16 15:26:171666瀏覽

寫元件時有時想把一些元件特性相關的 CSS 樣式封裝在 JS 裡,這樣比較內聚,改起來方便。 JS 動態插入 CSS 兩個步驟:建立1、一個 style 物件
2.使用 stylesheet 的 insertRule 或 addRule 方法加入樣式

一、查看樣式表

先看下 document.styleSheets,隨意開啟一個頁面

其中前三個是透過 link 標籤引入的 CSS 文件,第四個是透過 style 標籤內聯在頁面裡的 CSS。有以下屬性

 每一個 cssRule 又有以下屬性

其中的 cssText 正是寫在 style 的原始碼。 

二、動態插入 CSS
首先,需要建立一個 style 對象,返回其 stylesheet 物件

/*
 * 创建一个 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。
完整程式碼如下

/*
 * 动态添加 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判斷的程式碼

/*
 * 动态添加 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);
 }
}();

以上就是JavaScript動態插入CSS的方法,希望對大家的學習有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn