JavaScript动态设置div的样式的方法
有时候需要根据需要动态设置div的样式,当然对于稍有经验的javascript开发者来说,这一切都是那么的简单,但是对于初学者或者说没有相关经验的开发者来说可能就是一个不大不小的难关,下面就通过实例简单介绍一下如何实现此效果。
代码实例如下:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<metaname="author"content="http://www.softwhy.com/"/>
<head>
<title>动态设置div的样式</title>
<styletype="text/css">
div{
width:50px;
height:50px;
background:red;
margin-top:10px;
}
.bg{
background-color:blue;
}
</style>
<scripttype="text/javascript">
window.onload=function(){
varfirstDiv=document.getElementById("firstDiv");
varsecondDiv=document.getElementById("secondDiv");
varfirst=document.getElementById("first");
varsecond=document.getElementById("second");
first.onclick=function(){
firstDiv.style.backgroundColor="green";
}
second.onclick=function(){
secondDiv.className="bg";
}
}
</script>
</head>
<body>
<divid="firstDiv"></div>
<divid="secondDiv"></div>
<inputtype="button"value="使用style方式"id="first"/>
<inputtype="button"value="使用className方式"id="second"/>
</body>
</html>
以上代码实现了我们的要求,不过是用了两种方法,一种是style方式,一种是className方式。
特别注意:
1.使用style时,像background-color这种符合单词属性要使用驼峰写法(第二个单词首字母大写),写成backgroundColo这种形式。
2.使用className时,属性值是class样式名称,但是前面不能加点(.)。
PS:JavaScript动态改变div属性的实现方法
本文实例讲述了JavaScript动态改变div属性的实现方法。分享给大家供大家参考。具体如下:
这里可以通过JS动态改变div属性,样式等
<scripttype="text/javascript">
varoBox=document.getElementById('box');
varoDiv=document.getElementById('div1');
varaInput=document.getElementsByTagName('input');
varaAttr=['width','height','backgroundColor','display','display'];
varaValue=['200px','200px','red','none','block'];
for(varlen=aInput.length,i=0;i<len;i++){
aInput[i].index=i;//索引
aInput[i].onclick=function(){
//重置按钮,cssText清空DIV属性
if(this.index==aInput.length-1)oDiv.style.cssText="";
//设置DIV属性
property(oDiv,aAttr[this.index],aValue[this.index]);
};
}
//控制DIV属性
functionproperty(obj,attr,value){
obj.style[attr]=value;
}
</script>
希望本文所述对大家的javascript程序设计有所帮助。