History Api使用演示

h5新增的一个特性即在history对象上 新增了pushState 和 replaceState 接口 配合在window对象上新增的popState事件使用
为什么要用它:因为通过historyapi可以实现 url跳转的时候不刷新当前页面,因此 可以用来制作单页应用(SPA)
 
下面是个小例子:
 
 
切换到历史记录里查看,调用pushstate的时候插入了新的记录:

 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>

猜你喜欢

转载自www.cnblogs.com/wlink/p/10470057.html