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:触发 调用历史记录
Document*{
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;
}
var list = document.getElementById('list');
var con = document.getElementById('con');
var json = {
'小米': '小米商城',
'华为':'华为商城',
'苹果': '苹果商城'
};
var str = '';
var arr = [];
for (var key in json) {
str +='
' + key + '';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;
}
案例:tab切换,记录内容
image.png
image.png
image.png