第一种方法:
通过获取内部css的style值来获取:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jsObject.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
function test4(eventobj){
if(eventobj.value=="黑色"){
var di=document.getElementById("div1");
di.style.backgroundColor="black";
}else if(eventobj.value=="红色"){
var di=document.getElementById("div1");
di.style.backgroundColor="red";
}
}
</script>
</head>
<body>
<div id="div1" style="width:300px;height:300px; background-color:red;position:float">
div1
</div>
<input type="button" value="黑色" onclick="test4(this)"/>
<input type="button" value="红色" onclick="test4(this)"/>
</body>
</html>
第二种:通过获取外部引入css的参数:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jsObject.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./my1.css">
<script type="text/javascript">
function test4(eventobj){
//获取引入的第一个css的样式表
var ocssRules = document.styleSheets[0].rules; //注意ie中使用document.styleSheets[0].rules 火狐、opera使用:document.styleSheets[0].cssrules
//获取css样式表中第一个样式
var style2 =ocssRules[0];
if(eventobj.value=="黑色"){
style2.style.backgroundColor="black";
}else if(eventobj.value=="红色"){
style2.style.backgroundColor="red";
}
}
</script>
</head>
<body>
<div class="style1">
div1
</div>
<input type="button" value="黑色" onclick="test4(this)"/>
<input type="button" value="红色" onclick="test4(this)"/>
</body>
</html>