js選項卡簡單程式碼例項

admin發表於2017-04-16

分享一段程式碼例項,它利用原生js實現了簡單的選項卡切換功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0px;
  padding: 0px;
}
ul li {
  list-style-type: none;
}
a {
  text-decoration: none;
  color: #fff;
}
#box {
  margin:50px;
  overflow:hidden;
}
#nav li {
  padding-left: 8px;
  padding-top: 3px;
  width: 90px;
  height: 25px;
  margin: 0;
  border: 1px solid #999;
  border-bottom: 0;
  float: left;
  background: #ccc;
}
#antzone div {
  width: 395px;
  height: 150px;
  background: #694bb7;
  border: 1px solid #999;
  border-top: 0;
  display: none;
}
</style>
<script type="text/javascript">
window.onload = function() {
  var anniu1 = document.getElementById('nav').getElementsByTagName('li');
  var neirong = document.getElementById('antzone').getElementsByTagName('div');
  for (var index = 0; index < anniu1.length; index++) {
    anniu1[index].index = index;
    anniu1[index].onclick = function () {
      for (var index = 0; index < anniu1.length; index++) {
        anniu1[index].style.background = '#ccc';
        neirong[index].style.display = 'none';
      }
      this.style.background = '#694bb7';
      neirong[this.index].style.display = 'block';
    }
  }
}
</script>
</head>
<body>
<div id="box">
  <div id="nav">
    <ul>
      <li style="background:#694bb7;"><a href="javascript:;">螞蟻部落一</a></li>
      <li style="border-left:0;"><a href="javascript:;">螞蟻部落二</a></li>
      <li style="border-left:0;"><a href="javascript:;">螞蟻部落三</a></li>
      <li style="border-left:0;"><a href="javascript:;">螞蟻部落四</a></li>
    </ul>
  </div>
  <div id="antzone">
    <div style="display:block;">js教程</div>
    <div>div教程</div>
    <div>css教程</div>
    <div><a href="http://www.softwhy.com" target="_blank">www.softwhy.com</a></div>
  </div>
</div>
</body>
</html>

相關文章