<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>history模式实现路由</title>
</head>
<style>
.div1 {
width: 300px;
height: 300px;
display: none;
text-align: center;
line-height: 300px;
}
.index {
background-color: red;
}
.about {
background-color: green;
}
</style>
<body>
<a href="javascript:jump('/index')">首页</a>
<a href="javascript:jump('/about')">关于页</a>
<div class="div1 index">首页</div>
<div class="div1 about">关于页</div>
<script>
// 跳转后不能刷新页面会404 需要后台配合重定向来解决这问题
function jump(path) {
// 重写URL路径为传入的名称
// 1.
history.pushState(null, 'page', path);
// 2.
// history.replaceState(null,'page',path);
// 获取页面所有组件
let pages = document.querySelectorAll('.div1');
// 获取新的page
let newPage = document.querySelector(path.replace('/', '.'));
// 隐藏所有
pages.forEach(item => item.style.display = 'none');
// 显示新page
newPage.style.display = 'block';
}
</script>
</body>
</html>