首页 > 技术文章 > url的hash和HTML5的history

birdy-silhouette 2020-12-22 17:52 原文

url的hash和HTML5的history

第一种方法是改变url的hash值。

**显示当前路径 : **location.href

http://localhost:8080/# 

切换路径: location.hash = 'foo'

http://localhost:8080/#/foo

第二种方式是使用HTML5的history模式

#1 pushState() 与 back()

location.href
>>> http://localhost:8080

history.pushState({},'','foo')
>>> http://localhost:8080/foo

history.pushState({},'','about')
>>> http://localhost:8080/about

history.pushState({},'','bar')
>>> http://localhost:8080/bar

history.back()
>>> http://localhost:8080/about

history.back()
>>> http://localhost:8080/foo
1234567891011121314151617

把url看做一个栈,pushState()向栈中放入一个url,而back()删除掉栈顶的url,页面总是呈现栈顶的url。
这种方式保留了历史记录,页面可以返回。

#2 replaceState()

location.href
>>> http://localhost:8080

history.replaceState({},'','home')
>>> http://localhost:8080/home

history.replaceState({},'','about')
>>> http://localhost:8080/about
12345678

直接改变了url,这种方式没有保存历史记录,页面不可返回。

#3 go()与forward()

//这两个方法一般与pushState()结合使用
//pushState()会使浏览器保留一个url的历史记录,而go()方法与forward()方法都可以改变这个历史记录的状态

history.go(-1) 等价于 history.back()
history.go(1) 等价于 history.forward()
history.go(-2)
history.go(2)
...

推荐阅读