gavanwanggw

导航

使用history.pushState()和popstate事件实现AJAX的前进、后退功能

上一篇文章中。我们使用location.hash来模拟ajax的前进后退功能。使用location.hash存在以下几个问题:

1.使用location.hash会导致地址栏的url发生变化。用户体验不够友好。

2.location.hash产生的历史记录无法改动。每次hash改变都会导致产生一个新的历史记录。

3.location.hash仅仅是1个字符串,不能存储非常多状态相关的信息。

为了解决这些问题,HTML5中引入了history.pushState()、history.replaceState()、popstate事件来处理浏览器历史记录的问题。

以下的代码能够达到跟location.hash同样的效果,能够看到地址栏url不会改变。

<!DOCTYPE html> 
<html>
<head>
	<meta charset="utf-8">
	<script type="text/javascript" src="jquery-1.11.1.min.js"></script>		
	<script type="text/javascript">		
	
		var currentPageIndex = 0;
				
		window.onload = function(){
			currentPageIndex = 0;
			showPageAtIndex(currentPageIndex);
			addHistory(currentPageIndex);
		}
		
		// onpopstate能够监控state变化
		window.onpopstate = function(e){
			if(history.state)
			{
				var state = history.state;
				showPageAtIndex(state.id);
			}
		}
				
		function toNextPageWhenClick()
		{
			currentPageIndex++;
			
			if(isValidPageIndex(currentPageIndex))
			{
				showPageAtIndex(currentPageIndex);
				addHistory(currentPageIndex);
			}
			else
			{
				return;
			}
		}
		
		function showPageAtIndex(id)
		{
			$("div[id!="+id+"]").hide();
			$("#"+id).show();
			
			if(isHomePage(id))
			{
				$("input").attr("value","current is home page,next page=1");
			}
			else if(isLastPage(id))
			{
				$("input").attr("value","current page="+id+", it is the end.");
			}
			else
			{
				$("input").attr("value","current page="+id+",next page="+(id+1));
			}
		}
		
		function isValidPageIndex(id)
		{
			return id <= 5;
		}
		
		function isLastPage(id)
		{
			return id == 5;
		}
		
		function isHomePage(id)
		{
			return id == 0;
		}
		
		// 添加历史记录
		function addHistory(id)
		{
			history.pushState({"id":id},"","");
		}
	</script>
	
	<style>
		.navigate{
			height:100px;
			width:300px;
			background-color:#0000ff;
			display:none;
		}
		
		.home{
			height:100px;
			width:300px;
			background-color:#00ff00;
			display:none;
		}
		
		.last{
			height:100px;
			width:300px;
			background-color:#ff0000;
			display:none;
		}
	</style>
</head> 
<body>
	<input type="button" value="" onclick="toNextPageWhenClick();">
	
	<div class="home" id="0">HOME PAGE</div>
	<div class="navigate" id="1">ajax1</div>
	<div class="navigate" id="2">ajax2</div>
	<div class="navigate" id="3">ajax3</div>
	<div class="navigate" id="4">ajax4</div>
	<div class="last" id="5">last page</div>
</body>
</html>




posted on 2017-04-24 17:18  gavanwanggw  阅读(168)  评论(0编辑  收藏  举报