亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript動態(tài)設(shè)置div的樣式的方法

 更新時間:2015年12月26日 09:56:36   作者:程序員小菜  
這篇文章主要介紹了JavaScript動態(tài)設(shè)置div的樣式的方法的相關(guān)資料,需要的朋友可以參考下

有時候需要根據(jù)需要動態(tài)設(shè)置div的樣式,當然對于稍有經(jīng)驗的javascript開發(fā)者來說,這一切都是那么的簡單,但是對于初學者或者說沒有相關(guān)經(jīng)驗的開發(fā)者來說可能就是一個不大不小的難關(guān),下面就通過實例簡單介紹一下如何實現(xiàn)此效果。

代碼實例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<head>
<title>動態(tài)設(shè)置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> 

以上代碼實現(xiàn)了我們的要求,不過是用了兩種方法,一種是style方式,一種是className方式。

特別注意:

1.使用style時,像background-color這種符合單詞屬性要使用駝峰寫法(第二個單詞首字母大寫),寫成backgroundColo這種形式。

2.使用className時,屬性值是class樣式名稱,但是前面不能加點(.)。

PS:JavaScript動態(tài)改變div屬性的實現(xiàn)方法

本文實例講述了JavaScript動態(tài)改變div屬性的實現(xiàn)方法。分享給大家供大家參考。具體如下:

這里可以通過JS動態(tài)改變div屬性,樣式等

<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 = "";
   //設(shè)置DIV屬性
   property(oDiv, aAttr[this.index], aValue[this.index]);
  };
 }
 //控制DIV屬性
 function property(obj, attr, value){
  obj.style[attr] = value;
 }
</script>

希望本文所述對大家的javascript程序設(shè)計有所幫助。

相關(guān)文章

最新評論