abstrait:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>js控制div樣式案例</title><style>* {margin: 0;padding: 0;}#box {width: 200PX;he
<!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函數(shù)調(diào)用自定義的函數(shù)完成改變元素的樣式 -->
<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');
}
//自定義函數(shù),通過.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(),得到要改變樣式的元素,第二步編寫自定義具體修改樣式到函數(shù),第三步在指定的元素的后面利用onclick()調(diào)用自定義的函數(shù)完成樣式的改變!
Professeur correcteur:天蓬老師Temps de correction:2019-01-29 13:02:31
Résumé du professeur:這是我第一次看到彩色代碼的提交, 寫得非常的完整,基本的DOM操作也都有, 設(shè)置樣式不僅可以用屬性,還可以用方法,例如: setAttribute()