摘要:(1)定义div初始样式(2)定义函数:获取对象,为对象的style属性重新赋值: <script type="text/javascript"> &nbs
(1)定义div初始样式
(2)定义函数:获取对象,为对象的style属性重新赋值:
<script type="text/javascript">
var obj = document.getElementById('box1')
function changeH() {
obj.style.height = "300px";
}
function changeW() {
obj.style.width = "300px";
}
function changeC() {
obj.style.backgroundColor = "#D6E9C6";
}
function reset() {
obj.style.height = "80px";
obj.style.width = "80px";
obj.style.backgroundColor = "#5BC0DE";
}
//将display设置为none即可隐藏
function hide() {
obj.style.display="none";
}
//同理,设置为block即可显示
function show() {
obj.style.display="block";
}
</script><!>window.onload=function(){}是等待所有的内容如图片、js、css等都加载完之后才执行的,主要特点是会覆盖前面的赋值。
(3)添加button,在onclick事件中调用函数;
<input type="button" value="变高" onclick="changeH()"/>
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js Change Style</title>
<style type="text/css">
#box1{width: 80px; height: 80px; background-color: #5BC0DE;
position: absolute; top: 40%; left: 40%;}
#box2{width: 320px; height: 30px;
position: absolute; top: 30%; left: 40%;}
input{margin: 0px 0px;}
</style>
<script type="text/javascript">
// var obj = document.getElementById('box1')
var obj
window.onload=function(){
obj = document.getElementById('box1')
}
function changeH() {
obj.style.height = "300px";
}
function changeW() {
obj.style.width = "300px";
}
function changeC() {
obj.style.backgroundColor = "#D6E9C6";
}
function reset() {
obj.style.height = "80px";
obj.style.width = "80px";
obj.style.backgroundColor = "#5BC0DE";
}
function hide() {
obj.style.display="none";
}
function show() {
obj.style.display="block";
}
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2">
<input type="button" value="变高" onclick="changeH()"/>
<input type="button" value="变宽" onclick="changeW()"/>
<input type="button" value="变色" onclick="changeC()"/>
<input type="button" value="重置" onclick="reset()"/>
<input type="button" value="隐藏" onclick="hide()"/>
<input type="button" value="显示" onclick="show()"/>
</div>
</body>
</html>END
批改老师:灭绝师太批改时间:2018-11-03 09:13:07
老师总结:案例写的非常全面,还有备注的习惯很好……继续加油……