监听浏览器地址栏变化、改变浏览器地址栏url

监听变化

if( ('onhashchange' in window) && ((typeof document.documentMode==='undefined') || document.documentMode==8)) {
	// 浏览器支持onhashchange事件
	window.onhashchange = function () {
		// TODO,对应的操作
	};
}else{
	// TODO 通过定时器进行检测
	var old_hash = '';
	setInterval(function() {
		if(window.location.hash != old_hash){
			old_hash = window.location.hash;
			// TODO,对应的操作
		}
	}, 300)
}

·

改变地址栏

function updateUrlParameter(url, key, value) {
	if (!value) {
		return url;
	}
	var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
	var separator = url.indexOf('?') !== -1 ? "&" : "?";
	if (url.match(re)) {
		return url.replace(re, '$1' + key + "=" + value + '$2');
	} else {
		return url + separator + key + "=" + value;
	}
}

// 可以根据需要自行改变
var newUrl = updateUrlParameter(window.location.href,'page', '5');
window.history.replaceState({path: newUrl}, '', newUrl);

·

以上方法可以配合使用 http://www.putyy.com/article/11 中的parseURL函数

LW放下的博客
请先登录后发表评论
  • latest comments
  • 总共0条评论