您的位置:首页 > Web前端 > JavaScript

JS 操作style属性

2016-05-04 22:06 591 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>操作style属性</title>
<style>
#div1{
width:100px;
height:100px;
background:red;
}
</style>
<script>

function setStyle(name,value){
var oDiv=document.getElementById('div1');

oDiv.style[name]=value; //操作属性方法二:[’属性名‘]里面属性名可用变量代替
}
function changeEnd()
{
var oDiv=document.getElementById('div1');

oDiv.style.width=200+"px";    //操作属性方法一点.
oDiv.style.height=200+"px";  //不加“px”在chrome里是无法运行的!!!
}
</script>

<body>
</head>
<input type="button" value="变宽" onclick="setStyle('height','400px')"/>
<input type="button" value="变高" onclick="setStyle('width','400px')"/>
<input type="button" value="变绿" onclick="setStyle('background','blue')"/>
<input type="button" value="还原" onclick="changeEnd()"/>
<div id="div1"></div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: