虽然html5的history api是H5专门用来解决记录历史记录和单页面的方法,可是不少老式的浏览器并不支持它,因此通常遇到老式的浏览器会作一个polyfill使用以前的hashchange方法。javascript
另外一方面,html5的history api在实际使用的时候会和以前的hashchange方法的用法有稍微的不一样。css
history.pushState(data, title, path);
,其中data是一个本身定义的数据对象,title是标题,如今大部分浏览器还不支持,path是路径。具体和hashchange方法相似,惟一不一样的地方是,在用history.pushState改变url的时候,因为不会触发onpopstate事件,因此一些函数要放在history.pushState改变url以后处理(之前是直接由hashchange事件处理)。html
若是是用#符号的话,那么方法相似hashchange。html5
可是新的history api能够摒弃#字符,好比说react-router里面就是这么作的,具体怎么解决我尚未弄清楚。java
下面是我编写的一段测试代码供你们参考。直接复制并存为html文件,而后在服务器上打开便可。(由于history api须要一个域名,能够是locahost)react
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script type="text/javascript"> //hashchange事件,若是有hash值,则输出到oDiv。 function onPopstate(event) { if(history.state) { console.log(history.state.next); } if(history.state && history.state.next === 1){ $('#div1').hide(); $('#div2').show(); $('#div3').hide(); } else if(history.state && history.state.next === 2) { $('#div1').hide(); $('#div2').hide(); $('#div3').show(); } else { $('#div1').show(); $('#div2').hide(); $('#div3').hide(); } } //页面加载 window.onload=function (){ //加载时触发一次hashchange事件 $(window) .bind( 'popstate', onPopstate ) .trigger( 'popstate' ); //点击事件,把数组装在hash里面 document.getElementById("input1").onclick=function(){ history.pushState({next: 1}, null, 'next1.html'); $('#div1').hide(); $('#div2').show(); $('#div3').hide(); }; document.getElementById("input2").onclick=function(){ history.pushState({next: 2}, null, 'next2.html'); $('#div1').hide(); $('#div2').hide(); $('#div3').show(); }; document.getElementById("input3").onclick=function(){ history.pushState('', null, 'index.html'); $('#div1').show(); $('#div2').hide(); $('#div3').hide(); }; } </script> </head> <body> 主页=模块1,模块2页=模块2,模块3页=模块3 <input type="button" value="去模块2页" id="input1" /> <input type="button" value="去模块3页" id="input2" /> <input type="button" value="去主页" id="input3" /> <div id="div1">模块111111111111111111</div> <div id="div2">模块222222222222222222</div> <div id="div3">模块333333333333333333</div> </body> </html>