JavaScript动态插入CSS样式的方法与实现

作者:竹影时间:2026-10-29 18:43:11浏览:144

本文介绍如何在JavaScript中动态插入CSS样式,以提升组件样式的内聚性。通过创建style对象获取stylesheet,利用标准浏览器的insertRule或低版本IE的addRule方法添加规则。文章提供了兼容现代浏览器与旧版IE的代码实现,并说明了移动端场景下的简化方案。

动态插入CSS的基本思路

在开发组件时,有时需要将与组件特性相关的CSS样式封装在JavaScript中,这样可以提高代码的内聚性,便于后续修改。在JS中动态插入CSS主要包含两个步骤:首先创建一个style对象,然后使用stylesheet对象的insertRule或addRule方法来添加具体的样式规则。

查看样式表结构

一、查看样式表

首先观察document.styleSheets属性,可以随意打开一个页面进行查看。

动态插入CSS的基本思路

其中前三个是通过link标签引入的外部CSS文件,第四个则是通过style标签内联在页面中的CSS。这些样式表对象具有如下属性。

动态插入CSS的基本思路

每一个cssRule对象又包含如下属性。

动态插入CSS的基本思路

其中的cssText属性正是写在style标签中的源码内容。

动态插入CSS的实现代码

二、动态插入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的方法,希望对大家的学习有所帮助。

作者最新文章