有時候需要根據需要動態設置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程序設計有所幫助。



















