阅读 99

history 与 hashchange 原生 api

非刷新页面跳转(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 点击返回按钮 跳到前一页

原文:https://www.cnblogs.com/gsgs/p/12989831.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐