操作样式
**操作html的style属性中的样式**
添加样式
对象名.style.去掉样式中的-,并-后的首字母为大写
showdiv.style.backgroundColor="red";
当操作的css样式是js中的关键字时,需要在样式名前加css
showdiv.style.cssFloat="left";
一次性添加多个样式
showdiv.style.cssText="height:80px;weight:40px;color:red;background-color:blue";
删除样式
将样式值赋为空,就近原则,若标签中有style属性,css代码域中有属性,则会先将标签中style属性为空,显示css中属性
showdiv.style.backgroundColor="";
修改样式
和添加样式相同
showdiv.style.border="solid 2px orange";
**通过类选择器className**
添加修改样式,首先在标签中声明class="类选择器名"
对象名.className=另一个类选择器名
<div id="div01" class="common"></div>
div01.className="common2";
方式二:
div.classList.add(样式1,样式2,...);
div.classList.toggle(样式名,布尔值); true添加/false移出
删除样式
对象名.className="";
div.clssList.remove(样式1,样式2,...);
代码示例:
<html>
<head>
<title>js 操作元素样式</title>
<meta charset="utf-8"/>
<script type="text/javascript">
function t1()
{
var showdiv=document.getElementById("showdiv");
showdiv.style.backgroundColor="red";
showdiv.style.border="solid 2px orange";
showdiv.style.backgroundColor="";
}
function t2()
{
var div01=document.getElementById("div01");
alert(div01.className);
div01.className="common2";
div01.className="";
}
</script>
<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: orange;
}
</style>
</head>
<body>
<input type="button" value="添加样式" onclick="t1()"/>
<input type="button" value="className方式" onclick="t2()"/>
<hr />
<div id="showdiv">
</div>
<div id="div01" class="common">
</div>
</body>
</html>