国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-20 10:55:01
字體:
供稿:網(wǎng)友

有時候需要根據(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ì)有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 达拉特旗| 多伦县| 大姚县| 会理县| 乌兰县| 鹤壁市| 织金县| 北京市| 桃江县| 哈巴河县| 云南省| 清河县| 城口县| 贵港市| 彭州市| 忻州市| 五指山市| 同德县| 万全县| 邯郸市| 宽城| 察哈| 彰武县| 滦平县| 杭州市| 北碚区| 攀枝花市| 万宁市| 黑河市| 伊通| 武宁县| 赣州市| 赤水市| 临西县| 调兵山市| 莆田市| 祥云县| 南平市| 韩城市| 廉江市| 绵阳市|