html5路由概念中的history模式和hash模式的区别

1

这里的hash是指url尾巴后的#号及后面的字符。这里的#和css里的#是一个意思。hash即:#这里意味着锚点,本身是用来做页面定位的,她可以使对应id的<element>元素显示在可视区域内。由于hash值变化不会导致浏览器向服务器发出请求,而且hash改变会触发javascript语言的hashchange事件,浏览器的前进后退也能对其进行控制,所以人们在 html5 的 history 出现前,基本都是使用 hash 来实现前端路由的。前端开发中的路由概念就是<a>超级链接的意思,导航链接的意思。

举个例子:

改变#不触发网页加载

http://www.example.com/index.html#location1 
// 改成
http://www.example.com/index.html#location

转载:

window.history.pushState(state, title, url) 
// state:需要保存的数据,这个数据在触发popstate事件时,可以在event.state里获取
// title:标题,基本没用,一般传 null
// url:设定新的历史记录的 url。新的 url 与当前 url 的 origin 必须是一樣的,否则会抛出错误。url可以是绝对路径,也可以是相对路径。
//如 当前url是 https://www.baidu.com/a/,执行history.pushState(null, null, './qq/'),则变成 https://www.baidu.com/a/qq/,
//执行history.pushState(null, null, '/qq/'),则变成 https://www.baidu.com/qq/

window.history.replaceState(state, title, url)
// replaceState与 pushState 基本相同,但replaceState是修改当前历史记录,而 pushState 是创建新的历史记录

window.addEventListener("popstate", function() {
    // 监听浏览器前进后退事件,pushState 与 replaceState 方法不会触发              
});

window.history.back() // 后退
window.history.forward() // 前进
window.history.go(1) // 前进一步,-2为后退两步,window.history.lengthk可以查看当前历史堆栈中页面的数量

猜你喜欢

转载自blog.csdn.net/zy103118/article/details/109668577