HTML5 history 页面历史记录
2020-04-01 本文已影响0人
Do_Du
DOM window 对象通过history对象提供了对浏览器历史的访问。
跳转属性
back(): 向后跳转
forward(): 向前跳转
go(): 跳转至第n页
// 在history中向后跳转
window.history.back();
window.history.go(-1);
// 向前跳转
window.history.forward();
window.history.go(1);
// 当前页
window.history.go(0);
添加和修改历史记录中的条目
pushState(状态对象,标题(可为空),URL(可选的)):记录历史记录
window.onpopstate:触发 调用历史记录
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.body{
background: gray;
}
#box{
width: 800px;
height: 400px;
background-color: #ddd;
margin: 100px auto;
display: flex;
justify-content: space-around;
align-items: center;;
}
ul{
width: 200px;
height:300px;
border: 1px solid #fff;
border-bottom: none;
}
li{
list-style: none;
line-height: 100px;
border-bottom: 1px solid #fff;
text-align: center;
}
#con{
width: 500px;
height: 300px;
border: 1px solid#fff;
}
</style>
<body>
<!-- 移动端app没有记录历史记录 模仿记录历史记录-->
<div id="box">
<ul id="list"></ul>
<div id="con"></div>
</div>
<script>
var list = document.getElementById('list');
var con = document.getElementById('con');
var json = {
'小米': '小米商城',
'华为':'华为商城',
'苹果': '苹果商城'
};
var str = '';
var arr = [];
for (var key in json) {
str +='<li data-name="'+key+'">' + key + '</li>';
arr.push(json[key])
}
list.innerHTML = str;
console.log('arr',arr);
//以上完成渲染数据
var lis = list.querySelectorAll('li');
for (var i = 0; i < arr.length; i++) {
lis[i].index = i;
console.log('lis',lis[i]);
lis[i].onclick = function () { // 实现点击切换
con.innerHTML = arr[this.index];
window.history.pushState(arr[this.index],'',this.dataset['name']);
}
}
window.onpopstate = function (e) {
console.log('11')
var e = e || e.target;
console.log(e)
con.innerHTML = e.state;
}
</script>
</body>
</html>
案例:tab切换,记录内容
![](https://img.haomeiwen.com/i16766625/105c916c0334af28.png)
![](https://img.haomeiwen.com/i16766625/166353415ed1b084.png)
![](https://img.haomeiwen.com/i16766625/8c7f099dde4cac3f.png)