有時候需要根據(jù)需要動態(tài)設(shè)置div的樣式,當(dāng)然對于稍有經(jīng)驗(yàn)的javascript開發(fā)者來說,這一切都是那么的簡單,但是對于初學(xué)者或者說沒有相關(guān)經(jīng)驗(yàn)的開發(fā)者來說可能就是一個不大不小的難關(guān),下面就通過實(shí)例簡單介紹一下如何實(shí)現(xiàn)此效果。
代碼實(shí)例如下:
<!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> 以上代碼實(shí)現(xiàn)了我們的要求,不過是用了兩種方法,一種是style方式,一種是className方式。
特別注意:
1.使用style時,像background-color這種符合單詞屬性要使用駝峰寫法(第二個單詞首字母大寫),寫成backgroundColo這種形式。
2.使用className時,屬性值是class樣式名稱,但是前面不能加點(diǎn)(.)。
PS:JavaScript動態(tài)改變div屬性的實(shí)現(xiàn)方法
本文實(shí)例講述了JavaScript動態(tài)改變div屬性的實(shí)現(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è)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答