一般 SPA 中前端路由有2中實現方式,本文會簡單快速總結這兩種方法及其實現:javascript
咱們都知道 url 中能夠帶有一個 hash, 好比下面 url 中的 page2
css
https://www.abc.com/index.html#page2
window 對象中有一個事件是 onhashchange,如下幾種狀況都會觸發這個事件:html
4)瀏覽器前進後退可能致使hash的變化,前提是兩個網頁地址中的hash值不一樣。前端
這個事件有 2 個重要的屬性:oldURL 和 newURL,分別表示點擊先後的 urljava
<!-- 該頁面路徑爲 https://www.abc.com/index.html --> <a href="#page2">click me</a> <script type="text/javascript"> window.onhashchange = function(e){ console.log(e.oldURL); //https://www.abc.com/index.html console.log(e.newURL); //https://www.abc.com/index.html#page2 } </script>
這樣咱們能夠這樣創建一個 DOMcss3
<nav> <a class="item active" href="#page1" data-target="#index">page1</a> <a class="item" href="#page2" data-target="#info">page2</a> <a class="item" href="#page3" data-target="#detail">page3</a> <a class="item" href="#page4" data-target="#show">paga4</a> <a class="item" href="#page5" data-target="#contact">paga5</a> </nav> <div class="container"> <div class="page active" id="index"> <h1>This is index page</h1> </div> <div class="page" id="info"> <h1>This is info page</h1> </div> <div class="page" id="detail"> <h1>This is detail page</h1> </div> <div class="page" id="show"> <h1>This is show page</h1> </div> <div class="page" id="contact"> <h1>This is contact page</h1> </div> </div>
爲了好看咱們加上 css, 比較重要的樣式已經在代碼裏標出來了。git
body{ padding:0; margin: 0; } h1{ margin: 0 0 0 160px; } nav{ width: 150px; height: 150px; float: left; } nav a{ display: block; background: #888; border: 1px solid #fff; border-top: none; width: 150px; font-size: 20px; line-height: 30px; text-align: center; color: #333; text-decoration: none; } .container{ height: 154px; } /* page 部分比較重要*/ .page{ display: none; } .page.active{ display: block; } /* page 部分比較重要*/ nav a.active, .container{ background: #ddd; border-right-color: #ddd; }
重點是下面的 javascript,這裏 DOM 操做咱們藉助 jQuerygithub
var containers = $('.container'); var links = $('.item'); window.onhashchange = function(e){ var currLink = $('[href="'+ location.hash + '"]').eq(0); var target = currLink.attr('data-target'); currLink.addClass('active').siblings('a.item').removeClass('active'); $(target).addClass('active').siblings('.page').removeClass('active'); }
實現的邏輯不難,可是利用 hash 老是沒有所謂前端路由的那種味,必然也不是主流方法。一樣的效果若是需求簡單不考慮兼容性的話,利用 css3 中 target 僞類就能夠實現,這不是本文的重點,這裏就不展開了。瀏覽器
做爲一種主流方法,咱們下面看看 history 如何實現。網站
history 其實瀏覽器歷史棧的一個藉口,去過只有 back()
, forward()
, 和 go()
方法實現堆棧跳轉。到了 HTML5 , 提出了 pushState()
方法和 replaceState()
方法,這兩個方法能夠用來向歷史棧中添加數據,就好像 url 變化了同樣(過去只有 url 變化歷史棧纔會變化),這樣就能夠很好的模擬瀏覽歷史和前進後退了。而如今的前端路由也是基於這個原理實現的。
這裏咱們先簡單認識一下 history:
go(n) 方法接受一個整數參數, n大於0會發生前進 n 個歷史棧頁面; n小於0會後退 -n 個歷史棧頁面;
forward() 前進一個頁面
back() 後退一個頁面
pushSate(dataObj, title, url) 方法向歷史棧中寫入數據,其第一個參數是要寫入的數據對象(不大於640kB),第二個參數是頁面的 title, 第三個參數是 url (相對路徑)。這裏須要說明的有3點:
replaceState(dataObj, title, url) 這個和上一個的區別就在於它不是寫入而是替換棧頂記錄,其他和 pushState 如出一轍
History 還有1個靜態只讀屬性:
History.length:固然歷史堆棧長度
瞭解了這麼多,那麼能夠研究一下如何利用 history 實現一個前端路由了,這裏只考慮 javascript 部分,css 部分和上文一致。這裏咱們修改部分 html:
<a class="item active" href="/page1.html" data-target="#index">page1</a> <a class="item" href="/page2.html" data-target="#info">page2</a> <a class="item" href="/page3.html" data-target="#detail">page3</a> <a class="item" href="/page4/subpage1.html" data-target="#show">paga4-1</a> <a class="item" href="/page5/subpage2.html" data-target="#contact">paga4-2</a>
咱們修改了 a 標籤的 href,這樣的連接看上去纔不是錨點了,不過這個過程咱們要處理比較多的工做。首先爲了簡單一些,咱們的這裏僅僅對 .html
或沒有擴展名結尾的連接設置前端路由:
// 經過委託的方法組織默認事件 var routerRxp = /\.html$|\/[^.]*$|/; $(document).click(function(e){ var href = e.target.getAttribute('href'); if(href && routrRxp.test(href)){ e.preventDefault(); } });
然後咱們在點擊時把數據寫入歷史棧,並控制 class 效果:
$(document).click(function(e){ var href = e.target.getAttribute('href'); if(href && routerRxp.test(href)){ var id = e.target.getAttribute('data-target'); history.pushState({targetId: id}, 'History demo', href); $(id).addClass('active').siblings('.page').removeClass('active'); e.preventDefault(); } });
到這裏,連接就能夠點擊了,可是瀏覽器的前進後退還不能用,咱們加入 onpopstate 事件:
$(window).on('popstate',function(e){ var id = e.originalEvent.state.targetId; $(id).addClass('active').siblings('.page').removeClass('active'); });
這樣前進後退就能夠用了,可是咱們發現這樣並不能退回主頁,由於咱們的主頁默認就是 page1 標籤頁,因此沒有爲主頁添加 state,簡單處理就讓其本身刷新好啦:
var indexPage = location.href; $(window).on('popstate',function(e){ if(location.href === indexPage){ location.reload(); } var id = e.originalEvent.state.targetId; $(id).addClass('active').siblings('.page').removeClass('active'); });
注意,這裏不能使用重置 location.href 的方法刷新,那樣就不能再前進了。
下面附上 history 方法的完整 js 代碼
var indexPage = location.href; var routerRxp = /\.html$|\/[^.]*$|/; $(document).click(function(e){ var href = e.target.getAttribute('href'); if(href && routerRxp.test(href)){ var id = e.target.getAttribute('data-target'); history.pushState({targetId: id}, 'History demo', href); $(id).addClass('active').siblings('.page').removeClass('active'); e.preventDefault(); } }); $(window).on('popstate',function(e){ if(location.href === indexPage){ location.reload(); } var id = e.originalEvent.state.targetId; $(id).addClass('active').siblings('.page').removeClass('active'); });
最後,關於兩種方法有一些比較重要的特性總結一下:
e.originalEvent.state
屬性是存在硬盤裏的,觸發該事件後讀取的歷史棧信息是經過 pushState 或 replaceState 寫入的纔會有值,不然改屬性爲 null。history.state
和 e.originalEvent.state
殊途同歸,並且前者能夠在該事件以外任何地方隨時使用。