码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-06-11 16:59:20      阅读:16278      评论:0      收藏:0      [点我收藏+]

标签:浏览器历史记录   location.hash缺点   hash和pushstate区别   

上一篇文章中,我们使用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>


技术分享
技术分享

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

标签:浏览器历史记录   location.hash缺点   hash和pushstate区别   

原文地址:http://blog.csdn.net/aitangyong/article/details/46457855

(1)
(5)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!