zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS styleSheets对象:读取页面的所有CSS样式

JS对象CSS 页面 所有 读取 样式
2023-06-13 09:12:01 时间
在 DOM 2 级规范中,使用 styleSheets 对象可以访问页面中所有样式表,包括用 style 标签定义的内部样式表,以及用 link 标签或 @import 命令导入的外部样式表。

cssRules 对象包含指定样式表中所有的规则(样式)。提示,IE 支持 rules 对象表示样式表中的规则。可以使用下面代码兼容不同的浏览器:


var cssRules = document.styleSheets[0].cssRules || document.styleSheets[0].rules;

在上面代码中,先判断浏览器是否支持 cssRules 对象,如果支持则使用 cssRules(非 IE 浏览器),否则使用 rules(IE 浏览器)。

在下面示例中,通过 style 标签定义一个内部样式表,为页面中的 div id= box 标签定义 4 个属性:宽度、高度、背景色和边框。然后在脚本中使用 styleSheets 访问这个内部样式表,把样式表中的第 1 个样式的所有规则读取出来,在盒子中输出显示。代码如下:


 style type= text/css 

#box {

 width: 400px;

 height: 200px;

 background-color:#BFFB8F;

 border: solid 1px blue;

 /style 

 script 

window.onload = function(){

 var box = document.getElementById( box 

 var cssRules = document.styleSheets[0].cssRules || document.styleSheets[0].rules; //判断浏览器类型

 box.innerHTML = h3 盒子样式 /h3 

 box.innerHTML += br 边框: + cssRules[0].style.border; //读取cssRules的border属性

 box.innerHTML += br 背景: + cssRules[0].style.backgroundColor; //读取cssRules的background-color属性

 box.innerHTML += br 高度: + cssRules[0].style.height; //读取cssRules的height属性

 box.innerHTML += br 宽度: + cssRules[0].style.width; //读取cssRules的width属性

 /script 

 div id= box /div 

演示效果如下:

JS styleSheets对象:读取页面的所有CSS样式

cssRules(或 rules)的 style 对象在访问 CSS 属性时,使用的是 CSS 脚本属性名,因此所有属性名称中不能使用连字符。例如:


cssRules[0].style.backgroundColor;

23302.html

CSShtmljavaJavaScript