您好,欢迎访问一九零五行业门户网

JavaScript动态插入CSS的方法_javascript技巧

写组件时有时想把一些组件特性相关的 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的方法,希望对大家的学习有所帮助。
其它类似信息

推荐信息