123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <!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>
- .box div{
- width: 200px;
- height: 120px;
- background-color: #aaa;
- color: #fff;
- font-size: 40px;
- font-weight: bolder;
- text-align: center;
- line-height: 120px;
- }
- .box{
- display: flex;
- }
- .box .active{
- background-color: #111;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <div class="tab-btn active">first</div>
- <div class="tab-btn">second</div>
- <div class="tab-btn">third</div>
- </div>
- <script>
- let tabBtns = document.querySelectorAll('.tab-btn');
- let hashArr = ["first","second","third"];
- tabBtns.forEach((item,index)=>{
- item.onclick = function(){
- // 管理选中状态
- // tabBtns.forEach((item)=>{
- // item.classList.remove("active");
- // });
- // this.classList.add("active");
- // 管理hash
- location.hash = hashArr[index]
- }
- })
- // 监听hash变化
- window.onhashchange = function(){
- // 获取hash值
- let hashVal = location.hash.slice(1);
- // 根据hash值,管理选中状态
- // 获取hash值对应的索引
- // let index = hashArr.indexOf(hashVal);
- let index = hashArr.findIndex((item)=>{
- // if(item == hashVal){
- // return true;
- // }
- return item == hashVal;
- })
- tabBtns.forEach((item)=>{
- item.classList.remove("active");
- });
- tabBtns[index].classList.add("active");
- }
- </script>
- </body>
- </html>
|