<html>
<head>
<title>js操作属性的样式</title>
<meta charset="UTF-8"/>
<!--声明css-->
<style type="text/css">
#showdiv{
width: 200px;
height: 200px;
border: solid 1px;
}
.common{
width: 200px;
height: 200px;
border: solid 1px;
}
.common2{
width: 200px;
height: 200px;
border: solid 1px;
background-color: blue;
}
</style>
<!--
js操作元素样式:
获取元素对象
通过style属性
元素对象名.style.样式名="样式值";//添加或者修改
元素对象名.style.样式名="";//删除样式
注意:以上操作,操作的是HTML的style属性声明里的样式,而不是其他的CSS代码域中的样式
通过className
元素对象名.className="新的值";//添加类选择器样式或者修改类选择器样式
元素对象名.className="";//删除
-->
<!--声明js-->
<script type="text/javascript">
//js给元素操作样式--style
//js给元素添加样式
function testAddCss(){
var showdiv=document.getElementById("showdiv");
showdiv.style.backgroundColor="green";
}
//js修改元素样式
function testUpdateCss(){
var showdiv=document.getElementById("showdiv");
showdiv.style.border="solid 2px blue";
}
//js删除样式
function testDelete(){
var showdiv=document.getElementById("showdiv");
showdiv.style.border="";
}
function ex(){
var showdiv=document.getElementById("showdiv");
showdiv.style.backgroundColor="green";
showdiv.style.border="solid 2px blue";
showdiv.style.border="";
}
//js操作样式--className
//注意:关键字是蓝色,不能用于命名
function testOperCss(){
var div01=document.getElementById("div01");
//获取
alert(div01.className);
//添加或修改
div01.className="common2";
//删除
div01.className="";
}
</script>
</head>
<body>
<h3>js操作属性的样式</h3>
<input type="button" name="" id="" value="测试给元素添加样式--style" onclick="testAddCss()"/>
<input type="button" name="" id="" value="测试给元素修改样式--style" onclick="testUpdateCss()"/>
<input type="button" name="" id="" value="测试给元素删除样式--style" onclick="testDelete()"/>
<input type="button" name="" id="" value="style" onclick="ex()"/>
<hr />
<div id="showdiv" style="border: solid brown;">
</div>
<hr />
<input type="button" name="" id="" value="测试元素样式--className"onclick="testOperCss()" /><hr />
<div id="div01" class="common">
</div>
</body>
</html>