<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <nav id="nav"> <ul> <li class="act">选卡1</li> <li>选卡2</li> <li>选卡3</li> <li>选卡4</li> </ul> </nav> <div id="container"> <section class="tab" style="background-color: rgb(7, 60, 234)">别忘送她一束花</section> <section class="tab" style="background-color: rgb(72, 228, 16)">别忘送她一束花</section> <section class="tab" style="background-color: rgb(131, 9, 245)">别忘送她一束花</section> <section class="tab" style="background-color: rgb(245, 16, 207)">别忘送她一束花</section> </div> </body> </html>
* { text-align: center; } nav li { display: inline; width: 40%; text-decoration: none; padding: 15px; } li:hover { background-color: rgb(6, 190, 251); } section { height: 300px; }
<script> window.onload = function () { // 根据指定id获取值对象 var nav = document.getElementById('nav'); // 通过标签名得到元素 var oNav = nav.getElementsByTagName('li'); // 根据指定id获取值对象 var container = document.getElementById('container'); // 获取class名 var oDiv = container.getElementsByClassName('tab'); // 遍历 for (var i = 0; i < oNav.length; i++) { // 循环遍历 oNav[i].index = i; //index是原本的属性 oNav[i].onclick = function () { for (var i = 0; i < oNav.length; i++) { // 去掉样式然后隐藏 oNav[i].className = ''; oDiv[i].style.display = "none"; } this.className = 'act'; oDiv[this.index].style.display = "block" } for (var m = 1; m < oNav.length; m++) { // 遍历不让他显示多个div,只能点一个出现一个 oNav[m].className = ''; oDiv[m].style.display = "none"; } } }; </script>