javascript控制css样式所有样式代码实例汇总

伊谢尔伦
伊谢尔伦 原创
2017-07-19 16:43:04 1173浏览

记录一下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样式所有样式代码实例汇总的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。