JavaScript點選設定背景顏色的選項卡程式碼

螞蟻小編發表於2018-07-02

本章節分享的例項程式碼也是一個選項卡,只不過能夠設定背景顏色而已。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#red {
  width:260px;
  height:200px;
  background:#FF0000;
  display:none;
}
#green {
  width:260px;
  height:200px;
  background:#00FF00;
  display:none;
}
#yellow {
  width:260px;
  height:200px;
  background:#FFFF00;
  display:none;
}
#blue {
  width:260px;
  height:200px;
  background:#0000FF;
  display:none;
}
</style>
<script type="text/javascript">
window.onload=function() {
  var btn=document.getElementsByTagName('input');
  var div=document.getElementsByTagName('div');
  for (var i=0;i<btn.length;i++) {
    btn[i].index=i;
    btn[i].onclick=function() {
      for (var i=0;i<btn.length;i++) {
        btn[i].style.background = '';
      }
      switch (this.value) {
        case '紅色': 
          this.style.background = '#FF0000';
          break;
        case '綠色': 
          this.style.background = '#00FF00';
          break;
        case '黃色': 
          this.style.background = '#FFFF00';
          break;
        case '藍色': 
          this.style.background = '#0000FF';
          break;
      }
      for (var i=0;i<btn.length;i++) {
        div[i].style.display = '';
      }
      div[this.index].style.display = 'block';
    }
  }
};
</script>
</head>
<body>
<input type="button" id="btn1" value="紅色" style="background-color: #FF0000" />
<input type="button" id="btn2" value="綠色" />
<input type="button" id="btn3" value="黃色" />
<input type="button" id="btn4" value="藍色" />
<div id="red" style="display: block;"> </div>
<div id="green"> </div>
<div id="yellow"> </div>
<div id="blue"> </div>
</body>
</html>

相關文章