JS修改CSS的定义
当需要批量修改某些元素的样式时,可以直接用JS修改CSS的定义
<style type="text/css">
div{
height:300px;
width:300px;
border:1px #003399 solid;
background-color:#006633;
}
</style>
<script language="JavaScript" type="text/javascript">
if(document.all){//兼容IE
document.styleSheets[0].rules[0].style.height="100px";
}else{//兼容firefox
document.styleSheets[0].cssRules[0].style.height="100px";
}
//alert(document.getElementsByTagName('style')[0].innerHTML);
</script>
写成函数,由于样式名只能用数字来索引,所以用了DOM遍历(此函数来源于:http://tb.blog.csdn.net/TrackBack.aspx?PostId=1885195)
<style>
.exampleA{}
.exampleB{}
</style>
<script>
function changecss(theClass,element,value) {
var cssRules;
if (document.all) {
cssRules = 'rules';
}
else if (document.getElementById) {
cssRules = 'cssRules';
}
for (var S = 0; S < document.styleSheets.length; S++){
for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
document.styleSheets[S][cssRules][R].style[element] = value;
}
}
}
}
</script>
<span A</span>
<span B</span>
<span A</span>
<input type="button" value="Change A Red" onclick="changecss('.exampleA','color','red')"/><input type="button" value="Change A Black" onclick="changecss('.exampleA','color','black')"/>