首页 技术 正文
技术 2022年11月16日
0 收藏 948 点赞 3,779 浏览 1699 个字

一、popstate用来做什么的?
简而言之就是HTML5新增的用来控制浏览器历史记录的api。

二、过去如何操纵浏览器历史记录?
window.history对象,该对象上包含有length和state的两个值,在它的__proto__上继承有back、forward、go等几个功能函数
在popstate之前,我们可以利用back、forward、go对history进行后退和前进操作。
例如:
history.back(); (后退一步,使用history.go(-1)也可实现后退效果)
弊端:只能操作前进后退,但是无法控制前进后要去哪,history.length都只会维持原来的状态

三、popstate的怎么用?
HTML5的新API扩展了window.history,使历史记录点更加开放了。可以存储当前历史记录点pushState、替换当前历史记录点replaceState、监听历史记录点popstate。

pushState、replaceState两者用法差不多。

使用方法:

history.pushState(data,title,url);
//其中第一个参数data是给state的值;第二个参数title为页面的标题,但当前所有浏览器都忽略这个参数,传个空字符串就好;第三个参数url是你想要去的链接;

replaceState用法类似,例如:history.replaceState(“首页”,””,location.href+ “#news”);

两者区别:pushState会改变history.length,而replaceState不改变history.length

通过下图我们可以对比看出pushState和replaceState的差别(注意看history.length的变化):

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>图解用HTML5的popstate如何玩转浏览器历史记录</title>
</head>
<body><span class="js-news">新闻</span>
<span class="js-music">音乐</span>
<script> var locationHref = location.href;
document.addEventListener("click", function (event) {
var target = event.target;
if (target.className == "js-news") {
history.pushState("首页", "", locationHref + "#news");
} else if (target.className == "js-music") {
history.pushState("音乐", "", locationHref + "#music");
}
}); /* document.addEventListener("click",function(event){
var target = event.target;
if(target.className == "js-news"){
history.replaceState("首页","",locationHref + "#news");
}else if(target.className == "js-music"){
history.replaceState("音乐","",locationHref + "#music");
}
});*/ window.addEventListener("popstate", function () {
console.log(history.state);
})
</script>
</body>
</html>
图解用HTML5的popstate如何玩转浏览器历史记录 图解用HTML5的popstate如何玩转浏览器历史记录

四、监听浏览器状态(popstate)变化事件
可以理解为监听浏览器后退、前进的操作,只要后退或者前进就会触发。在上面的demo中,我们预先做了如下操作:打开页面→点击“新闻”→点击“音乐”→再点击“新闻”,产生了4个history记录。然后监听浏览器后退和前进的状态变化,如下图所示:

图解用HTML5的popstate如何玩转浏览器历史记录

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