<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .active{ background: yellow; } </style> </head> <body> <div id="box"></div> <p id="p"></p> <script> let arr = ['新聞','體育','軍事','頭條']; let btns = document.getElementsByTagName('button'); let hashNum;//爲了對應btn的顏色 let hash = window.location.hash; //一上來先獲取hash if(!hash){//若是沒有 window.location.hash = 'p=0'; //強行設置一波0,這個時候直接就跑到了hashchange中 }else{ //若是有,就獲取hash值 hashNum = window.location.hash.split('=')[1]*1; p.innerHTML = arr[hashNum]; } arr.forEach((e,i)=>{ let btn = document.createElement('button'); btn.innerHTML = e; btn.className = hashNum!=undefined && (e==arr[hashNum]?"active":''); btn.onclick = function(){ // for(let i=0;i<btns.length;i++){ // btns[i].className = ''; // } // this.className = 'active'; // p.innerHTML = e; window.location.hash = 'p='+i; } box.appendChild(btn) }); window.onhashchange = function(){ for(let i=0;i<btns.length;i++){ btns[i].className = ''; } let i = window.location.hash.split('=')[1]*1; btns[i].className = 'active'; p.innerHTML = arr[i]; } </script> </body> </html>