下表中列举了 JavaScript history 对象中常用的属性及其描述:
属性 | 说明 |
length | 返回浏览历史的数目,包含当前已经加载的页面。 |
scrollRestoration | 利用浏览器特性,使我们在返回上一页或者下一页时,将页面滚动到之前浏览的位置,该属性有两个值,分别是 auto(表示滚动)与 **nual(表示不滚动)。 |
state | 返回浏览器在当前 URL 下的状态信息,如果没有调用过 pushState() 或 replaceState() 方法,则返回默认值 null。 |
示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<script type="text/javascript">
document.write(history.length + "<br>");
document.write(history.scrollRestoration + "<br>");
document.write(history.state + "<br>");
</script>
</body>
</html>
运行结果如下:
5
auto
null
下表中列举了 JavaScript history 对象中常用的方法及其描述:
→ 按钮来实现同样的效果。示例代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<button onclick="myBack()">back()</button>
<button onclick="myForward()">forward()</button>
<button onclick="myGo()">go()</button>
<button onclick="myPushState()">pushState()</button>
<button onclick="myReplaceState()">replaceState()</button>
<script type="text/javascript">
function myBack(){
history.back();
}
function myForward(){
history.forward();
}
function myGo(){
var num = prompt('请输入一个整数', '1');
history.go(num);
}
function myPushState(){
var state = { 'page_id': 1, 'user_id': 5 }
var title = 'JavaScript'
var url = 'index.html'
history.pushState(state, title, url)
console.log(history.state);
}
function myReplaceState(){
var state = { 'page_id': 3, 'user_id': 5 }
var title = 'history'
var url = 'index.html'
history.replaceState(state, title, url)
console.log(history.state);
}
</script>
</body>
</html>
*声明:内容来源于网络收集和整理,版权归原著所有,如来源信息有误或侵犯权益,请联系站长作修改和删除处理。