<!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>
History路由实现的简单原理
最新推荐文章于 2022-09-17 00:23:27 发布