HTML5 历史管理

//html5历史管理
/**
 * onhashchange:事件;当hash值变化的时候就会触发
 * history : 
 * -pushState :三个参数:数据标题 地址(可选)
 * -popstate事件:读取数据event.state
 * 		网址是虚假的,需在服务器指定对应页面,不然刷新找不到页面
 */
//onhashchange
var oBtn = document.getElementById("button");
var oDiv = document.getElementById("div");
var obj = {};
oBtn.onclick = function(){
	var num = randomNum(35,7);
	oDiv.innerHTML = num;
	var oRD = Math.random();
	obj.oRD = num;
	window.location.hash = oRD;
}

window.onhashchange = function(){
	var num = obj[window.location.hash.substring(1)] || '';
	oDiv.innerHTML = num;
}

function randomNum(alls,now){
	var arr = [];
	var newarr = [];
	for(var i=1;i<=alls;i++){
		arr.push(i);
	}

	for(var i=0;i<now;i++){
		newarr.push(arr.splice(Math.floor(Math.random()*arr.length),1))
	}
	return newarr;

}


//history
var iNow = 1;
oBtn.onclick = function(){
	var num = randomNum(35,7);
	oDiv.innerHTML = num;
	history.pushState(num,'');
	history.pushState(num,'',iNow++); //地址改变但为虚假
}
window.popstate = function(ev){
	var num = ev.state || '';
	oDiv.innerHTML = num;
}

你可能感兴趣的:(HTML5 历史管理)