JavaScript动态插入CSS样式的方法与实现
本文介绍如何在JavaScript中动态插入CSS样式,以提升组件样式的内聚性。通过创建style对象获取stylesheet,利用标准浏览器的insertRule或低版本IE的addRule方法添加规则。文章提供了兼容现代浏览器与旧版IE的代码实现,并说明了移动端场景下的简化方案。
动态插入CSS的基本思路
在开发组件时,有时需要将与组件特性相关的CSS样式封装在JavaScript中,这样可以提高代码的内聚性,便于后续修改。在JS中动态插入CSS主要包含两个步骤:首先创建一个style对象,然后使用stylesheet对象的insertRule或addRule方法来添加具体的样式规则。
查看样式表结构
一、查看样式表
首先观察document.styleSheets属性,可以随意打开一个页面进行查看。

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

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

其中的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的方法,希望对大家的学习有所帮助。
JS怎么使用classList添加、删除和切换class
2026-11-05 17:26:02
网页开发三者分工:HTML结构、CSS样式与JavaScript交互怎么协作
2026-11-05 12:51:22
JS解析URL参数时怎么处理中文乱码和特殊字符
2026-11-05 12:47:23
js-cookie 存储 JSON 对象:自动序列化与反序列化技巧
2026-11-05 12:36:26
marked.js 快速上手:安装与基础 Markdown 转 HTML 示例
2026-11-05 09:32:53
