前端hash

单页面应用:hash
Hash:#
(1)代表网页中的一个位置,例:#print,代表页面中print的位置
(2)http请求不包含#,#是指导浏览器动作的
(3)#后面的字符,被浏览器解析成标志符,不会被发送到服务端
(4)改变#,不触发网页重载,滚动到相应的位置
(5)改变#,会改变浏览器的访问历史,会增加一个浏览记录,对IE6,IE7不成立
(6)window.location.hash 读取#值,可读可写,读时,判断网页状态是否改变,写时,在不重载网页的前提下,增加一条历史记录
(7)onhashchange事件:当#改变时,会触发这个事件
例子:
index.html文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		<a href="#/red">red</a>
		<a href="#/yellow">yellow</a>
		<a href="#/green">green</a>
		<script src="./js/hash.js"></script>
		
	</body>
</html>

hash.js文件


//定义一个router构造函数
function Router(){
	this.routes={};
	this.current='';
}
Router.prototype.route = function(path,fn){
	this.routes[path] = fn;//向routes里添加路由
}
Router.prototype.update = function(){//hash发生change的时候
	//知道当前的地址
	//根据属性名触发相对应的函数
	this.current = window.location.hash.slice(1);//获取#后面的地址
	this.routes[this.current]();
}
Router.prototype.inint = function(){//添加监听,页面初次加载,hash发生change
	window.addEventListener('load',this.update.bind(this),false);//第三个参数表示是捕获还是冒泡,true是捕获,false是冒泡
	window.addEventListener('hashchange',this.update.bind(this),false);
	
}
//router函数挂载到window对象上,这样就可以全局都能用到这个函数
window.Router = new Router();
window.Router.inint();//初始化window.Router添加监听
let body = document.body;
Router.route('/red',function(){//跳转路由的方法
	changeBgColor('red');
});
Router.route('/yellow',function(){
	changeBgColor('yellow');
});
Router.route('/green',function(){
	changeBgColor('green');
})
function changeBgColor(color){
	body.style.background = color;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值