最近看到vue-router的HTML5 History 模式路由的实现,然后顺便又去研究了一下HTML5 的 History,以下是自己的一些理解,顺便用jquery写 一个实现类似vue-router里面HTML5 History 模式路由器,以达到练练手,熟悉熟悉的目的。
一、history.pushState
history.pushState(state, title, url);上面第一和第二个参数可以为空,主要就是第三个参数,表示新历史纪录的地址,浏览器在调用pushState()方法后不会去加载这个URL,新的URL不一定要是绝对地址,如果它是相对的,它一定是相对于当前的URL
二、history.replaceState
history.replaceState(state, title, url);window.history.replaceState 和 window.history.pushState 类似,不同之处在于 replaceState 不会在 window.history 里新增历史记录点,其效果类似于 window.location.replace(url) ,都是不会在历史记录点里新增一个记录点的。
三、window.onpopstate
来监听url的变化
window.addEventListener("popstate", function() {
var currentState = history.state;
/*
* 触发事件后要执行的程序
*/
});
//或者
window.onpopstate = function(){}javascript脚本执行 window.history.pushState 和 window.history.replaceState 不会触发 onpopstate 事件,在浏览器点击前进或者后退会触发
谷歌浏览器和火狐浏览器在页面第一次打开的反应是不同的,谷歌浏览器奇怪的是回触发 onpopstate 事件,而火狐浏览器则不会
四、下面贴一个类似vue-router的HTML5模式的例子,纯属加深理解,写的很粗糙。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 History 模式(第二版)</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<style type="text/css">
.container-bg{width:1000px; overflow: hidden; margin-right: 0 auto;}
.pagination{width: 1000px; background-color: #d8d8d8; height: 30px; line-height: 30px;}
.pagination li{width: 100px; height: 30px; background: red; float: left; cursor: pointer; color:#fff; margin: 0 10px 0 0;}
</style>
</head>
<body>
<div class="container-bg">
<ul class="pagination">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="ptting"></ul>
</div>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">









