记录一下js控制css所使用的方法.
使用javascript更改某个css class的属性...
<style type="text/css">
.orig {
display: none;
}
</style>
你想要改变把他的display属性由none改为inline。
解决办法: 在ie里:
document.stylesheets[0].rules[0].style.display = "inline";
在firefox里:
document.stylesheets[0].cssrules[0].style.display = "inline";
讨论: 可以做一个函数来搜索特定名字的style对象:
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;
}
}
}
}
然后只要:
getstyle(".orig").display = "inline";
就可以了。
------------------ 注意 document.stylesheets[0].rules[0].style 这个 stylesheets[0]数组的下标是代表本页的第n个css样式表,它的下级rules[0]的数组下标表示的则是这个样式表中的第n个样式,例如:
<style type="text/css">
.s{display="none";}
.w{display="none";}
</style>
修改s则: document.stylesheets[0].rules[0].style.display='inline';
修改w则:document.stylesheets[0].rules[1].style.display = 'inline';
注意:css和html结合的方式必须为<link rel="stylesheet" type="text/css" href="" /> 或<style></style>的时候以上方法可行,如@import 则不行.
下面记录一下js访问css中的样式:
用javascript获取和设置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中不好使
两者兼容的方式写成
window.getcomputedstyle?window.getcomputedstyle(id,null).backgroundcolor:id.currentstyle["backgroundcolor"];
如果是获取背景色,这种方法在firefox和ie中的返回值还是不一样的,ie中是返回#ffff99样子的,而firefox中返回rgb(238, 44, 34)
值得注意的是:window.getcomputedstyle(id,null)这种方式不能设置样式,只能获取,要设置还得写成类似这样id.style.background=#ee2c21;
在ie中currentstyle只能以只读方式获取样式.
以上就是javascript控制css样式所有样式代码实例汇总的详细内容。