菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
112
0

history 与 hashchange 原生 api

原创
05/13 14:22
阅读数 51976

非刷新页面跳转(history跳转或者location.hash 跳转)

window.onpopstate = console.log
window.onhashchange = console.log
1. history.pushState({a:1,b:2}, 'title', '/test')   // /test
2. history.pushState({test:2,b:33}, 'title2', '/test2') // /test2
3. history.back()  // /test  log: {state:{a:1,b:2},...other}
4. history.forward() // /test2 log: {state:{test:2,b:33}, ...other}
5. history.back()
6. history.pushState({test: 3, b:44}, 'title3', '/test3') // history.length === 2 /test2被删除
7. location.hash = '#test3' // 会立刻触发onpopstate与hashchange 并且增加history记录。
8. history.pushState(null,'','#a') // 不会触发history与hashchange
9. history.back()     // 触发history与hashchange

非刷新跳转总结

  1. replaceState与pushState 相似,会替换替换url, 不会增加history长度
  2. 不在history最顶层的时pushState 会将此url 上层的记录替换为 pushSate的那条记录。
  3. hashchange 事件触发条件为,非pushState和replaceState 引起的hash变化
  4. onhashchange 事件触发条件为, 非pushState和replaceState 引起的 url变化。
  5. locaiton.href (location.hash) 操作只改hash 会触发2个事件。但是如果改了url 则会重新加载,不管是否有history记录。
  6. 刷新页面history依然保存

刷新页面跳转(location.href改变路径)

location.href的跳转(不含location.hash="#xxx"),属于刷新页面跳转,不管是history.back() 还是返回按钮,都会刷新页面,不会触发任何事件(hashchange,popstate)。
如果记录了history,则可以使用history.back(),但不一定能使用自带返回按钮,返回上一页,如下:

自动跳转 例如:a→b→c
  1. 点击返回按钮,c→a 页。
  2. 在页面加载时自动跳转到其他页面,如果在window.onload之前或者onload中的同步代码进行跳转, history不记录,如果在onload时机后的下一个事件队列进行跳转,则记录hisotry(上条规则仍然存在)。
手动跳转

记录history 点击返回按钮 跳到前一页

发表评论

0/200
112 点赞
0 评论
收藏