<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js控制div样式案例</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 200PX;
height: 200px;
background: #ccc;
margin: 100px auto;
margin-bottom: 30px;
}
.btn {
text-align: center;
}
.btn button {
width: 40px;
height: 30px;
border-radius: 5px;
margin-left: 10px;
background: #04703e;
color: white;
}
</style>
</head>
<body>
<div id="box"></div>
<div class="btn">
<!-- 在指定的元素中通过onclick函数调用自定义的函数完成改变元素的样式 -->
<button onclick="setwidth()">变宽</button>
<button onclick="setheight()"> 变高</button>
<button onclick="setbgr()">变色</button>
<button onclick="reset()">重置</button>
<button onclick="sethide()"> 隐藏</button>
<button onclick="setshow()">显示</button>
</div>
<script>
//找到要改变的元素。
var a;
window.onload = function () {
a = document.getElementById('box');
}
//自定义函数,通过.style.修改元素的属性值
function setwidth() {
a.style.width = "500px";
}
function setheight() {
a.style.height = "500px";
}
function setbgr() {
a.style.background = "green";
}
function reset() {
a.style.background = "#ccc";
a.style.width = "300px";
a.style.height = "300px";
}
function sethide() {
a.style.display = "none";
} function setshow() {
a.style.display = "block";
}
</script>
</body>
</html>
本案例中,主要通过第一步利用document.getElementById(),得到要改变样式的元素,第二步编写自定义具体修改样式到函数,第三步在指定的元素的后面利用onclick()调用自定义的函数完成样式的改变!