History路由实现的简单原理

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<style>
		* {
			/* global font */
			font-family: Verdana;
			font-size: 18px;
		}

		#root {
			display: flex;
			flex-direction: row;
		}

		#content {
			display: flex;
			display: block;
			width: 800px;
			height: 250px;
			/* vertically centered text */
			line-height: 250px;
			border: 2px solid #555;
			margin: 32px;
			text-align: center;
		}

		.route {
			cursor: pointer;
			justify-content: center;
			width: 150px;
			height: 50px;
			/* vertically centered text */
			line-height: 50px;
			position: relative;
			border: 2px solid #555;
			background: white;
			text-align: center;
			margin: 16px;
		}

		.route.selected {
			background: yellow;
		}
	</style>
	<body>
		<section id="root">
			<section class="route" id="home">/home</section>
			<section class="route" id="about">/about</section>
			<section class="route" id="gallery">/gallery</section>
			<section class="route" id="contact">/contact</section>
			<section class="route" id="help">/help</section>
		</section>
		<main id="content">Content loading...</main>
	</body>
	<script type="text/javascript">
		 window.onload = event => {
			//监听 路由的点击事件  执行push方法
			window["home"].addEventListener("click", event => push(event))
			window["about"].addEventListener("click", event => push(event))
			window["gallery"].addEventListener("click", event => push(event))
			window["contact"].addEventListener("click", event => push(event))
			window["help"].addEventListener("click", event => push(event))
		}
		 function select_tab(id) {
			 // 改变 路由按钮的样式
			document.querySelectorAll(".route").forEach(item => item.classList.remove('selected'));
			document.querySelectorAll("#" + id).forEach(item => item.classList.add('selected'));
		}
		function load_content(id) {
			//更新内容
			document.querySelector("#content").innerHTML = 'Content loading for /' + id + '...';
		}
		function push(event) {
			let id = event.target.id;
			select_tab(id);
			document.title = id;
			load_content(id);
			window.history.pushState({id}, `${id}`, `/page/${id}`);
		}
		 window.addEventListener("popstate", event => {
			let stateId = event.state.id;
			select_tab(stateId);
			load_content(stateId);
		});
		
	</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值