Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTML5之history对象方法扩展 #20

Open
Quickeryi opened this issue Jul 12, 2017 · 0 comments
Open

HTML5之history对象方法扩展 #20

Quickeryi opened this issue Jul 12, 2017 · 0 comments

Comments

@Quickeryi
Copy link
Owner

Quickeryi commented Jul 12, 2017

H5中扩展了history对象功能,使其具有更加丰富的能力,下面简单介绍一下!

pushState

  • 作用:在不刷新浏览器记录的情况下,新增浏览记录。这个方法的功能与直接修改location.hash类似
  • 参数:该方法有三个参数
    • state:一个与指定网址相关的状态对象,popstate事件触发时,该对象会传入回调函数,通过event.state访问,如果不需要这个对象,此处可以填null
    • title:新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null
    • url:新的网址,必须与当前页面处在同一个域,如果不是同一个域会报错,浏览器的地址栏将显示这个网址,需要特别注意的是,浏览器并不会检测新的url是否存在,即使不存在也不会报错。
  • 例子:
// 假设加入当前url为:http://www.c.com/
history.pushState(null, null, '?page=1');
// 此时当前url为:http://www.c.com/?page=1

replaceState

  • 作用:它修改浏览历史中当前纪录,所以当调用此方法后,原先的那一条记录就覆盖了
  • 参数:参数与pushState方法一模一样
  • 例子:
// 假设加入当前url为:example.com/example.html
history.pushState({page: 1}, 'title 1', '?page=1');
history.pushState({page: 2}, 'title 2', '?page=2');
history.replaceState({page: 3}, 'title 3', '?page=3'); // 此时example.com/example.html?page=2已经不存在了
history.back()
// url显示为http://example.com/example.html?page=1

history.back()
// url显示为http://example.com/example.html

history.go(2)
// url显示为http://example.com/example.html?page=3

history.state

  • 作用:属性返回当前页面的state对象,即上述方法的第一个参数

popstate事件

  • 作用:每当同一个文档的浏览历史(即history对象)出现变化时,就会触发popstate事件
  • 注意:调用replaceStatepushState不会触发该事件,调用backforwardgo或者点击浏览器的前进或后退时才会触发,有些浏览器在触发window.onload时也会触发popstate

hashchange事件

  • 作用:监听location.hash的变化
  • 例子:
window.addEventListener("hashchange", function () {
    console.log(1);
}, false);
location.hash = 'newhash';

一图概括

211e272f-76f2-44fe-a023-eff3af6fa359

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant