用Location对象和history对象修改页面url

用Location对象和history对象修改页面url

1.通过hash属性更改url

Location 对象包含有关当前 URL 的信息

  • Location.hash是URL的锚部分
  • Location.href是完整的URL

通过hash来更改url

location.hash = "newhash"

2.HTML5 history模式

2.1通过history对象的方法更改url

history对象,用来保存浏览历史

  • history.pushState() 浏览历史中添加记录
  • history.replaceState() 浏览历史中添加记录

通过pushState()来更改url

  • state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数。如果不需要这个对象,此处可以填null。
  • title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null。
  • url:新的资源
history.pushState({},'',home.html)

通过replaceState()来更改url

  • history.replaceState方法的参数与pushState方法一模一样,区别是它修改浏览历史中当前纪录。
history.replaceState({},'',home.html)

2.2浏览器页面前进和退后

退后

history.back()
//等价于
history.go(-1)

前进

history.forward()
//等价于
history.go(1)
posted @ 2022-12-07 15:11  鸭梨的药丸哥  阅读(100)  评论(0)    收藏  举报  来源