js控制属性的两种方法

下面以控制css属性为例,html属性也是一样

第一种     document.getElementById('div1').style.display='block'

第二种     document.getElementById('div1').style['display']='block'

两种的区别:第一种display不可以以参数的形式来使用,简而言之,第二种使用范围更广

下面以代码来更好的来区分

<html>

<head>
<title></title>
</head>
<style>
#div1{
width:100px;
height:200px;
background:red;
}
</style>
<script>
function setAttr(name,value){

document.getElementById('div1').style[name]=value
}
function setAttr1(name,value){
document.getElementById('div1').style.name=value    //设置属性会无效
}
</script>
<body>
<input type="button" onclick="setAttr('width','200px')" value="设置属性" />
<input type="button" onclick="setAttr1('width','300px')" value="设置属性"/>
<div id="div1"></div>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/superCwen/p/9763054.html
今日推荐