1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>History Api 使用演示</title> 8 </head> 9 <body> 10 <div class="wrapper"> 11 <ul class="nav"> 12 <li class="nav-item"> 13 first 14 </li> 15 <li class="nav-item"> 16 second 17 </li> 18 <li class="nav-item"> 19 third 20 </li> 21 </ul> 22 <div class="content"></div> 23 </div> 24 <script> 25 var menu = document.querySelectorAll('ul.nav>li'); 26 var content = document.querySelector('div.content'); 27 function initPage (page) { 28 menu.forEach(function(i,k){ 29 i.classList.remove('selected-item'); 30 }); 31 32 menu.forEach(function(i,k){ 33 if (i.innerText.toLowerCase().trim() === page) { 34 i.classList.add('selected-item'); 35 } 36 }); 37 content.innerText = `this is ${page.substring(1)} page`; 38 } 39 40 initPage(window.location.hash); 41 menu.forEach(function(i,k){ 42 i.addEventListener('click', function(e) { 43 var page = e.target.innerText.toLowerCase().trim(); 44 initPage(page); 45 // pushstate 會修改地址欄url並向歷史記錄添加一條記錄,不會刷新頁面! 46 window.location.hash = page; 47 history.pushState(null, page, window.location.hash); 48 }); 49 }); 50 51 /* 52 go back forward都會觸發popstate,這個方法會修改地址欄,不刷新頁面! 53 */ 54 window.addEventListener("popstate", function(e) { 55 initPage(window.location.hash); 56 }); 57 /* 58 錨點的改變會觸發hashchange事件,若是用錨點區分url能夠監聽此事件 59 */ 60 window.addEventListener('hashchange', function(e){ 61 var hash = window.location.hash; 62 console.log(`hash changed to ${hash}!`); 63 }); 64 </script> 65 </body> 66 </html>