标签:javascript css
下面先记录一下JS控制CSS所使用的方法.
关于rules和cssRules的浏览器兼容性,本人博文有测试记录:http://blog.csdn.net/u011043843/article/details/28276757
function getstyle(sname) {
for (var i=0;i<document.styleSheets.length;i++) {
var rules;
if (document.styleSheets[i].cssRules) {
rules = document.styleSheets[i].cssRules;
} else {
rules = document.styleSheets[i].rules;
}
for (var j=0;j<rules.length;j++) {
if (rules[j].selectorText == sname) {
//selectorText 属性的作用是对一个选择的地址进行替换.意思应该是获取RULES[J]的CLASSNAME.有说错的地方欢迎指正
return rules[j].style;
}
}
}
} 就可以了。
====================================
DOM标准引入了覆盖样式表的概念,当我们用document.getElementById("id").style.backgroundColor 获取样式时 获取的只是id中style属性中设置的背景色,如果id中的style属性中没有设置background-color那么就会返回空,也就是说如果id用class属性引用了一个外部样式表,在这个外部样式表中设置的背景色,那么不好意思
document.getElementById("id").style.backgroundColor 这种写法不好使,如果要获取外部样式表中的设置,需要用到window对象的getComputedStyle()方法,代码这样写window.getComputedStyle(id,null).backgroundColor
但是兼容问题又来了,这么写在firefox中好使,但在IE中不好使<style type="text/css">
.txt {
font-size: 30px; font-weight: bold; color: red;
}
</style>
<div id="tt">欢迎光临!</div>
<p><button onclick="setClass()">更改样式</button></p>
<script type="text/javascript">
function setClass()
{
document.getElementById( "tt" ).className = "txt";
}
</script> <div id="t2">欢迎光临!</div>
<p><button onclick="setSize()">大小</button>
<button onclick="setColor()">颜色</button>
<button onclick="setbgColor()">背景</button>
<button onclick="setBd()">边框</button>
</p>
<script type="text/javascript">
function setSize()
{
document.getElementById( "t2" ).style.fontSize = "30px";
}
function setColor()
{
document.getElementById( "t2" ).style.color = "red";
}
function setbgColor()
{
document.getElementById( "t2" ).style.backgroundColor = "blue";
}
function setBd()
{
document.getElementById( "t2" ).style.border = "3px solid #FA8072";
}
</script> javascript操作html元素CSS属性,布布扣,bubuko.com
标签:javascript css
原文地址:http://blog.csdn.net/u011043843/article/details/28594343