History Api使用演示

时间:2023-03-08 18:22:21
h5新增的一个特性即在history对象上 新增了pushState 和 replaceState 接口 配合在window对象上新增的popState事件使用
为什么要用它:因为通过historyapi可以实现 url跳转的时候不刷新当前页面,因此 可以用来制作单页应用(SPA)
下面是个小例子:
 History Api使用演示
切换到历史记录里查看,调用pushstate的时候插入了新的记录:
History Api使用演示

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>History Api 使用演示</title>
</head>
<body>
<div class="wrapper">
<ul class="nav">
<li class="nav-item">
first
</li>
<li class="nav-item">
second
</li>
<li class="nav-item">
third
</li>
</ul>
<div class="content"></div>
</div>
<script>
var menu = document.querySelectorAll('ul.nav>li');
var content = document.querySelector('div.content');
function initPage (page) {
menu.forEach(function(i,k){
i.classList.remove('selected-item');
}); menu.forEach(function(i,k){
if (i.innerText.toLowerCase().trim() === page) {
i.classList.add('selected-item');
}
});
content.innerText = `this is ${page.substring(1)} page`;
} initPage(window.location.hash);
menu.forEach(function(i,k){
i.addEventListener('click', function(e) {
var page = e.target.innerText.toLowerCase().trim();
initPage(page);
// pushstate 会修改地址栏url并向历史记录添加一条记录,不会刷新页面!
window.location.hash = page;
history.pushState(null, page, window.location.hash);
});
}); /*
go back forward都会触发popstate,这个方法会修改地址栏,不刷新页面!
*/
window.addEventListener("popstate", function(e) {
initPage(window.location.hash);
});
/*
锚点的改变会触发hashchange事件,如果用锚点区分url可以监听此事件
*/
window.addEventListener('hashchange', function(e){
var hash = window.location.hash;
console.log(`hash changed to ${hash}!`);
});
</script>
</body>
</html>