用JS中document.styleSheets控制cssRules规则
2016-06-02 08:41
387 查看
学习《JavaScript高级程序设计》的时候知道了一个小小的知识点……以前用JS控制写在html标签里用style属性的样式<h1
style="width:100px;">,可以用普通的DOM方法获得。例如theEl.style.width,但是如果是写在style标签下的样式<type="text/css">h1{width:100px;}</style>,这种方法就会输出空值。
这个时候必须用到cssRules集合才能取得、修改该样式的值。
[html] view
plain copy
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>css rules</title>
<style type="text/css">
#div1{width:100%;height:400px; background:red;}
</style>
<script>
window.onload=init;
function $(id){
return "string" == typeof id ? document.getElementById(id) : id;
}
function init(){
var ocssRules=document.styleSheets[0].cssRules || document.styleSheets[0].rules || window.CSSRule.STYLE_RULE;
var theEl=$("div1");
ocssRules[0].style.background="yellow";
alert(ocssRules[0].style.background);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
style="width:100px;">,可以用普通的DOM方法获得。例如theEl.style.width,但是如果是写在style标签下的样式<type="text/css">h1{width:100px;}</style>,这种方法就会输出空值。
这个时候必须用到cssRules集合才能取得、修改该样式的值。
[html] view
plain copy
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>css rules</title>
<style type="text/css">
#div1{width:100%;height:400px; background:red;}
</style>
<script>
window.onload=init;
function $(id){
return "string" == typeof id ? document.getElementById(id) : id;
}
function init(){
var ocssRules=document.styleSheets[0].cssRules || document.styleSheets[0].rules || window.CSSRule.STYLE_RULE;
var theEl=$("div1");
ocssRules[0].style.background="yellow";
alert(ocssRules[0].style.background);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
相关文章推荐
- CSS 块级元素 和 行级元素 的分类和区别。
- css实现背景透明文字不透明
- CSS 页面刷新添加和移除 class 样式
- css中的max-width
- 改变checkBox的背景样式
- css中的margin
- 《CSS权威指南》学习记录——内边距、边框、外边距
- 纯CSS3实现自行车动画 非常逼真
- css left right top bottom定位
- css2的几种特殊选择器
- TimePickerDialog样式配置与TimePicker模式选择
- css部分细节(持续更新)
- CSS-边距
- html怎么引用css
- css expression是什么鬼
- 纯CSS画的基本图形(矩形、圆形、三角形、多边形、爱心、八卦等)
- 自定义Progress样式(原生progress方式实现)
- css 添加换行
- css3动画库
- 20 个常用的 CSS 技巧