123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- *{
- margin: 0;
- padding: 0;
- }
- li{
- list-style: none;
- }
- .container{
- width: 500px;
- height: 300px;
- border:1px solid black;
- margin:100px auto;
- }
- .head-nav li{
- float: left;
- width: 100px;
- height: 50px;
- color: #fff;
- text-align: center;
- line-height: 50px;
- }
- .head-nav li:hover{
- cursor: pointer;
- }
- .head-nav{
- height: 50px;
- border-bottom: 1px solid black;
- background-color: black;
- }
- .head-nav .active{
- background-color: #aaa;
- color: #000;
- }
- .content-item{
- display: none;
- }
- .content .active{
- display: block;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <div class="head-nav">
- <ul>
- <li class="nav-item active">第一节课</li>
- <li class="nav-item">第二节课</li>
- <li class="nav-item">第三节课</li>
- <li class="nav-item">第四节课</li>
- </ul>
- </div>
- <div class="content">
- <div class="content-item active">
- <h2>第一节课</h2>
- <p>第一节课的内容</p>
- </div>
- <div class="content-item">
- <h2>第二节课</h2>
- <p>第二节课的内容</p>
- </div>
- <div class="content-item">
- <h2>第三节课</h2>
- <p>第三节课的内容</p>
- </div>
- <div class="content-item">
- <h2>第四节课</h2>
- <p>第四节课的内容</p>
- </div>
- </div>
- </div>
- <script>
- // 第一步获取元素
- // 获取导航按钮
- var navItem = document.getElementsByClassName("nav-item");
- // 获取内容区域
- var contentItem = document.getElementsByClassName("content-item");
- // 第二步循环为导航按钮绑定事件
- for(var i=0;i<navItem.length;i++){
- // 循环过程中保存i这个索引值
- navItem[i].index = i;
- navItem[i].onclick = function(){
- // 第三步移除所有被选中按钮
- for(var j=0;j<navItem.length;j++){
- navItem[j].classList.remove("active");
- contentItem[j].classList.remove("active");
- }
- // 第四步切换类名
- // 用this来代替当前所点击的按钮
- // 为当前点击的按钮添加“active”类
- this.classList.add("active");
- // 控制对应的内容显示 通过定义的index (索引)
- contentItem[this.index].classList.add("active");
- // console.log(this.index)
- }
- }
- </script>
- </body>
- </html>
|