使用javascript更改某个css class的属性

Achilles's picture

问题:
你想要修改某个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 == ".orig") {
				return rules[j].style;
			}
		}
	}
}

然后只要:

getstyle(".orig").display = "inline";

就可以了。

Comments

测试匿名评论

测试匿名评论

Achilles's picture

测试评论

测试评论

-------------
Achilles Xu

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <font>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.