单页面应用: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;
}