有时候需要根据需要动态设置div的样式,当然对于稍有经验的javascript开发者来说,这一切都是那么的简单,但是对于初学者或者说没有相关经验的开发者来说可能就是一个不大不小的难关,下面就通过实例简单介绍一下如何实现此效果。
代码实例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<!DOCTYPE html> <html> <head> <meta charset= " utf-8" >
<head> <title>动态设置div的样式</title> <style type= "text/css" >
div{ width:50px;
height:50px;
background:red;
margin-top:10px;
} .bg{ background-color:blue;
} </style> <script type= "text/javascript" >
window.onload= function (){
var firstDiv=document.getElementById( "firstDiv" );
var secondDiv=document.getElementById( "secondDiv" );
var first=document.getElementById( "first" );
var second=document.getElementById( "second" );
first.onclick= function (){
firstDiv.style.backgroundColor= "green" ;
}
second.onclick= function (){
secondDiv.className= "bg" ;
}
} </script> </head> <body> <div id= "firstDiv" ></div>
<div id= "secondDiv" ></div>
<input type= "button" value= "使用style方式" id= "first" />
<input type= "button" value= "使用className方式" id= "second" />
</body> </html> |
以上代码实现了我们的要求,不过是用了两种方法,一种是style方式,一种是className方式。
特别注意:
1.使用style时,像background-color这种符合单词属性要使用驼峰写法(第二个单词首字母大写),写成backgroundColo这种形式。
2.使用className时,属性值是class样式名称,但是前面不能加点(.)。
PS:JavaScript动态改变div属性的实现方法
本文实例讲述了JavaScript动态改变div属性的实现方法。分享给大家供大家参考。具体如下:
这里可以通过JS动态改变div属性,样式等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<script type= "text/javascript" >
var oBox = document.getElementById( 'box' );
var oDiv = document.getElementById( 'div1' );
var aInput = document.getElementsByTagName( 'input' );
var aAttr = [ 'width' , 'height' , 'backgroundColor' , 'display' , 'display' ];
var aValue = [ '200px' , '200px' , 'red' , 'none' , 'block' ];
for ( var len=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属性
function property(obj, attr, value){
obj.style[attr] = value;
}
</script> |
希望本文所述对大家的javascript程序设计有所帮助。