2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

HTML5中的History对象

HTML5标准之前


基本操作

1.forward(number) 加载histroy列表中的下一个URL

2.back(number) 加载histroy列表中的上一个URL

3.go(number) 根据当前所处的页面,加载 history 列表中的某个具体的页面。

例子:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>
</head>

<body>

<button onclick="forward()">前进(加载histroy列表中的下一个URL)</button>
<button onclick="now()">当下</button>
<button onclick="back()">后退(加载histroy列表中的上一个URL)</button>
<button onclick="go()">想去哪就去哪的go</button>

</body>
<script type="text/javascript" src="lodash.js"></script>
<script type="text/javascript">

function forward() {
	//forward()相当于go(1)
	window.history.forward();
}

function now() {
	//forward()相当于go(0)
	window.history.go(0);
}

function back() {
	//forward()相当于go(-1)
	window.history.back();
}

function go() {
	window.history.go(10);
}
</script>

</html>


HTML5标准后


history.pushState()

新的状态信息就会被加入到history状态栈(列表),而浏览器地址栏也会变成新的相对URL。

var stateObj = { foo: "bar" };
window.history.pushState(stateObj, "page 2", "newly.html");

但是:浏览器不会刷新,这样也不会发送请求。

pushState 不会触发 onpopstate

这里需要与window.location.href='./newly.html'这个操作方法区分开。因为这个会刷新url,且发送请求。

history.replaceState()

更新当前历史记录条目的状态对象或URL。

var stateObj = { foo: "bar" };
window.history.replaceState(stateObj, "page 1", "app.html");

不同于window.location.replace(url)浏览器不会刷新,这样也不会发送请求。

replaceState不会触发 onpopstate

图解:

onpopstate

onpopstate事件是用来监听URL发生变化的情况触发。


window.onpopstate = function(){

}

具体测试代码:
zqz_History对象

posted on 2017-02-21 12:57  qize  阅读(833)  评论(0编辑  收藏  举报

导航