『改变URL但不刷新页面』的两种方法

  • Post author:
  • Post category:其他




1.URL的hash

  • URL的hash也就是锚点(#),本质上是改变window.location的href属性
  • 可以通过直接赋值location.hash来改变href,但是页面不发生刷新
location.href
"http://localhost:8080/#/"
location.hash='/'
"/"
location.href
"http://localhost:8080/#/"
location.hash='/foo'
"/foo"
location.href
"http://localhost:8080/#/foo"



2.HTML5的history模式



history.pushState()

history.pushState({},'','/home')
undefined
location.href
"http://localhost:8080/home"
history.pushState({},'','/dome')
undefined
location.href
"http://localhost:8080/dome"



history.replaceState()

location.href
"http://localhost:8080/dome"
history.replaceState({},'','/foo')
undefined
location.href
"http://localhost:8080/foo"
history.replaceState({},'','/foo/bar')
undefined
location.href
"http://localhost:8080/foo/bar"



history.go()

location.href
"http://localhost:8080/foo/bar"
history.go(-1)
undefined
location.href
"http://localhost:8080/home#/"
history.go(-1)
undefined
location.href
"http://localhost:8080/#/foo"
history.go(1)
undefined
location.href
"http://localhost:8080/home#/"



版权声明:本文为qq_44824148原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。