js實現hash路由原理

簡單的上下佈局,點擊左側導航,中心內容跟對變化,主要技術是檢測路由的hashchange事件
在這裏插入圖片描述

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>hash路由demo</title>
	<style>
		body,html{
			margin: 0;
			width: 100%;
			height: 100%;
		}
		h1{
			margin: 0;
			height: 60px;
			background: #ccc;
		}
		#left{
			float: left;
			width: 200px;
			height: calc(100% - 60px);
			background: #168;
		}
		#main{
			height: calc(100% - 60px);
			width: calc(100% - 200px);
			background: #198;
			margin-left: 200px;
		}
	</style>
</head>
<body>
	<h1>hash 路由</h1>
		<div id="left">
			<li><a href="#/">默認值</a></li>
			<li><a href="#/a">aaaa</a></li>
			<li><a href="#/b">bbbb</a></li>
			<li><a href="#/c">cccc</a></li>
			<li><a href="#/d">dddd</a></li>
			<li><a href="#/e">eeee</a></li>
		</div>
		<div id="main">
			<div id="con"><b>默認值</b></div>
		</div>
	<script>
		window.onload = function(){
	
					function loadContent(con){
						document.getElementById("con").innerHTML = con
					}
					var hashRouter = {
						path: "/"
					}
					hashRouter.init = function(hash){
						let path = hash.substring(1)
						this.path = path
						router.map(function(ele,index){
							 if(path == ele.path){
								return loadContent(ele.component)
							}
						})
					}
					window.router = hashRouter
					router = [{
							  path: '/',
							  component: "<b>默認值</b>"
							},
							{
							  path: '/a',
							  component: "<b>aaaaaaaaaaaaaa</b>"
							},
							{
							  path: '/b',
							  component: "<b>bbbbbbbbbbbbbb</b>"
							},
							{
							  path: '/c',
							  component: "<b>cccccccccccccc</b>"
							},
							{
							  path: '/d',
							  component: "<b>ddddddddddddddd</b>"
							},
							{
							  path: '/e',
							  component: "<b>eeeeeeeeeeeeeeee</b>"
							}
					]
				    hashRouter.init(location.hash)
					window.onhashchange = function(){
						 hashRouter.init(location.hash)
					}
				
		}
	</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章