Div变换样式
今天我们来学习如何实现将一个div盒子变宽、变高和变绿,我们首先来看一下效果图。
接下来我们来分析一下代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>div变换样式</title>
<style>
#div1{
width: 200px;
height: 200px;
background: red;
margin-top: 5px;
}
</style>
<script>
function toWidth()
{
var oDiv=document.getElementById('div1');
oDiv.style.width='400px';
}
function toHeight()
{
var oDiv=document.getElementById('div1');
oDiv.style.height='400px';
}
function toGreen()
{
var oDiv=document.getElementById('div1');
oDiv.style.background='green';
}
</script>
</head>
<body>
<input type="button" value="变宽" onclick="toWidth()"/>
<input type="button" value="变高" onclick="toHeight()"/>
<input type="button" value="变绿" onclick="toGreen()"/>
<div id="div1"></div>
</body>
</html>
同样地,我们发现中间<script></script>的内容过于繁琐,我们同样采用函数传参的方法,定义两个变量(name,value),将<script></script>的内容改为:
<script>
function setStyle(name,value)
{
var oDiv=document.getElementById('div1');
oDiv.style[name]=value;
}
</script>
相比前面所写的是不是精简了许多,好了,今天的分享就到这里了。
愿你三冬暖,愿你春不寒,愿你天黑有灯,下雨有伞。