JS 控制CSS樣式表
2024-05-06 14:14:21
供稿:網友
下面先記錄一下JS控制CSS所使用的方法.
1.使用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";