用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 @   鸭梨的药丸哥  阅读(69)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示