用javascript操作CSS样式表

  使用javascriptDOM模型可以对链入或嵌入页面的CSS Stylesheet进行各种操作。演示代码如下(使用prototype库):

<html>
<head>
<script language=”javascript” src=”js/prototype.js”></script>
<link type=”text/css” rel=”stylesheet” href=”css/cssmanip.css” title=”test_sheet” />
</head>
<body>

<span class=”text_style bg_style”>
some text
</span>
<button onclick=”black_color();”>BLACK</button>
<button onclick=”white_color();”>white</button>

<script type=”text/javascript”>
Object.extend(document.styleSheets, {
get : function(name) {
for (var i=0; i<this.length; i++) {
if (this[i].title == name) return Object.extend( this[i], {
rule : function(selectorName) {
var aRules = this.cssRules;
for (var i=0; i<aRules.length; i++) {
if (aRules[i].selectorText == selectorName) return aRules[i];
}

     return null;
}
});
}

  return null;
}
});

var theStyle = document.styleSheets.get(’test_sheet’).rule(’.text_style’).style;

function black_color() {
theStyle.color = ‘black’;
}

function white_color() {
theStyle.color = ‘white’;
}
</script>

</body>
</html>

cssmanip.css如下:

.text_style {
color: white;
}

.bg_style {
background-color: black;
}


2,490 Responses to “用javascript操作CSS样式表