history和hash详解
一、history window.history(可直接写成history)指向History对象,它表示当前窗口的浏览历史。History对象保存了当前窗口访问过的所有页面网址 1. length history.length属性保存着历史记录的url数量,初始时该值为1,如果当前窗口先后访问了三个网址,那么history对象就包括3项,history.length=32.跳转方法:允许在浏览器历史之间移动 go() 接受一个整数为参数,移动到该整数指定的页面,比如history.go(1)相当于history.forward(),history.go(-1)相当于history.back(),history.go(0)相当于刷新当前页面back() 移动到上一个访问页面,等同于浏览器的后退键,常见的返回上一页就可以用back(),是从浏览器缓存中加载,而不是重新要求服务器发送新的网页forward() 移动到下一个访问页面,等同于浏览器的前进键如果移动的位置超出了访问历史的边界,以上三个方法并不报错,而是默默的失败3.history.pushState() 在浏览器历史中添加记录 if(!!(window.hostory && history.pushState)) { // 支持History API} else { // 不支持}以上代码可以用来检查当前浏览器是否支持History API。如果不支持的话可以考虑使用Polyfill库History.jshistory.pushstate()方法接受三个参数,以此为: state: 一个与指定网址相关的状态对象,popState事件触发时,该对象会传入回调函数,如果不需要这个对象,此处可填nulltitle: 新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填nullurl: 新的网址,必须与当前页面处在同一个域,浏览器的地址栏将显示这个网址假定当前网址是example.com/1.html,我们使用pushState方法在浏览记录(history对象)中添加一个记录 var stateObj = {foo:'bar'};history.pushState(stateObj,'page 2','2.html')添加上边这个新纪录后,浏览器地址栏立刻显示example.com/2.html,但不会跳转到2.html,甚至也不会检查2.html是否存在,它只是成为浏览历史中的新纪录。这时,你在地址栏输入一个新的地址,然后点击了后退按钮,页面的url将显示2.html;你再点击以此后退按钮,url将显示1.html总之,pushState方法不会触发页面刷新,只是导致了history对象发生变化,地址栏会有反应。如果pushState的url参数,设置了一个新的锚点值(即hash),并不会触发hashChange事件,如果设置了一个跨域网址,则会报错。 //报错history.pushState(null,null,'https://twitter.com/hello')上边代码中,pushState()想要插入一个跨域的网址,导致报错,这样设计的目的是防止恶意代码让用户以为他们是在另一个网站上 4. history.replaceState()history.replaceState()方法的参数和pushState()方法一摸一样,区别是它修改浏览器历史当中的记录假定当前页面是example.com/example.html history.pushState({page:1},'title 1','?page=1')history.pushState({page:2},'title 2','?page=2')history.replaceState({page:3},'title 3','?page=3')history.back() //url显示为example.com/example.html?page=1history.back() //url显示为example.com/example.htmlhistory.go(2) //url显示为example.com/example.html?page=35. history.state属性history.state返回当前页面的state对象 history.pushState({page:1},'title 1','?page=1')history.state //{page:1}5. popState 事件每当同一个文档的浏览历史(即history)出现变化时,就会触发popState事件需要注意:仅仅调用pushState方法或replaceState方法,并不会触发该事件,只有用户点击浏览器后退和前进按钮时,或者使用js调用back、forward、go方法时才会触发。另外该事件只针对同一个文档,如果浏览历史的切换,导致加载不同的文档,该事件不会被触发使用的时候,可以为popState事件指定回调函数 window.onpopstate = function (event) { console.log('location: ' + document.location); console.log('state: ' +JSON.stringify(event.state));};// 或者window.addEventListener('popstate', function(event) { console.log('location: ' + document.location); console.log('state: ' + JSON.stringify(event.state));});回调函数的参数是一个event事件对象,它的state属性指向pushState和replaceState方法为当前url所提供的状态对象(即这两个方法的第一个参数)。上边代码中的event.state就是通过pushState和replaceState方法为当前url绑定的state对象这个state也可以直接通过history对象读取history.state注意:页面第一次加载的时候,浏览器不会触发popState事件 ...