javascript如何動態設定div的樣式

admin發表於2017-02-20

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

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!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樣式名稱,但是前面不能加點(.)。

相關文章