原生js实现简单选项卡

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>选项卡</title>
  <style>
    #container div {
      width: 300px;
      height: 200px;
      border: 3px solid red;
      display: none;
      margin-top: 10px;
      text-align: center;
      line-height: 200px;
      font-size: 30px;
    }

    #container div.active {
      display: block;
    }

    button {
      outline: none;
      border: 2px solid gray;
      border-radius: 5px;
    }

    button.active {
      background-color: orange;
    }
  </style>
</head>
<body>
  <div id="wrap">
    <button class="active">选项一</button>
    <button>选项二</button>
    <button>选项三</button>
    <button>选项四</button>
    <div id="container">
      <div class="active">
		  内容一
		  <span>1</span>
		  <span>2</span>
		  <span>3</span>
		  <span>4</span>
		  <span>5</span>
	  </div>
      <div>内容二</div>
      <div>内容三</div>
      <div>内容四</div>
    </div>
  </div>
  <script>
    var oWrap = document.getElementById('wrap')
    var oBtn = oWrap.getElementsByTagName('button')
    var oCon = document.getElementById('container')
    var oDiv = oCon.getElementsByTagName('div')
    for (var i = 0; i < oBtn.length; i++) {
      oBtn[i].index = i
      oBtn[i].onclick = function () {
        for (var j = 0; j < oBtn.length; j++) {
          oBtn[j].style.backgroundColor = 'white'
          oDiv[j].style.display = 'none'
        }
        this.style.backgroundColor = 'orange'
        oDiv[this.index].style.display = 'block'
      }
    }
  </script>
</body>
</html>

  

上一篇:JS隐藏显示图片


下一篇:一个导航网站