【JS】【CSS】JavaScriptとCSSでタブ表示

ポイント

 * タブをCSSで表現

サンプル

<html>
<head>
<title>サンプル</title>
<style type="text/css">
#tab1, #tab2, #tab3 {
  float:left; // タブの表示を左並びに表示するため
  width:80px;
  background-color:#ffffff;
  border-width:1px;
  border-style:solid;
  cursor:pointer; // カーソルを指型にするため
  font-weight:100;
}
#canvas {
  clear:left;
  width:400px;
  height:100px;
  padding:1em 1em 1em 1em;
  border-width:1px;
  border-style:solid;
}
#content1, #content2, #content3 {
  display:none; // 非表示(タブの内容)
}
</style>
<script type="text/javascript">
function sample(id) {
  document.getElementById("tab1").style.color = "#000000";
  document.getElementById("tab1").style.backgroundColor = "#ffffff";
  document.getElementById("tab2").style.color = "#000000";
  document.getElementById("tab2").style.backgroundColor = "#ffffff";
  document.getElementById("tab3").style.color = "#000000";
  document.getElementById("tab3").style.backgroundColor = "#ffffff";
  
  document.getElementById(id).style.color = "#ffffff";
  document.getElementById(id).style.backgroundColor = "#ff0000";
  
  if (id == "tab1") {
    document.getElementById("canvas"). innerHTML
     = document.getElementById("content1"). innerHTML;
  } else if (id == "tab2") {
    document.getElementById("canvas"). innerHTML
     = document.getElementById("content2"). innerHTML;
  } else if (id == "tab3") {
    document.getElementById("canvas"). innerHTML
     = document.getElementById("content3"). innerHTML;
  }
}
</script>
</head>
<body>
<div>
  <div id="tab1" onclick="sample(id)">タブ1</div>
  <div id="tab2" onclick="sample(id)">タブ2</div>
  <div id="tab3" onclick="sample(id)">タブ3</div>
  <div id="canvas">ここにタブの内容が表示される(初期値としては、タブ1の内容が表示されるべきかな)</div>
</div>
<div id="content1">タブの中身1</div>
<div id="content2">タブの中身2</div>
<div id="content3">タブの中身3</div>
</body>
</html>