首页 技术 正文
技术 2022年11月14日
0 收藏 918 点赞 2,574 浏览 1502 个字

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>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,111
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,203
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,838
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,922