JavaScript動態設定div的樣式的方法,

來源:互聯網
上載者:User

JavaScript動態設定div的樣式的方法,

有時候需要根據需要動態設定div的樣式,當然對於稍有經驗的javascript開發人員來說,這一切都是那麼的簡單,但是對於初學者或者說沒有相關經驗的開發人員來說可能就是一個不大不小的難關,下面就通過執行個體簡單介紹一下如何?此效果。

代碼執行個體如下:

<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://www.softwhy.com/" /><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屬性,樣式等

<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程式設計有所協助。

您可能感興趣的文章:
  • javaScript 讀取和設定文件項目的樣式屬性
  • js setattribute大量設定css樣式
  • javascript 動態設定已知select的option的value值的代碼
  • IE6下JS動態設定圖片src地址問題
  • js 設定選中行的樣式的實現代碼
  • 使用JavaScript動態設定樣式實現代碼及示範動畫
  • 使用JavaScript動態設定樣式實現代碼(2)
  • js大量設定樣式的三種方法不推薦使用with
  • js動態設定div的值下例子
  • javascript設定金額樣式轉換保留兩位小數範例程式碼
  • JavaScript通過元素的ID和name設定樣式
  • 使用變數動態設定js的屬性名稱
  • js style動態設定table高度
  • javascript動態設定樣式style執行個體分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.