同一页面切换
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.pages>div{ display: none;}
</style>
</head>
<body>
<p><a href="#/">首页</a> | <a href="#/about">关于我们</a> | <a href="#/user">用户页面</a></p>
<div class="pages">
<div id="home">
<h1>首页内容</h1>
</div>
<div id="about">
<h1>关于页面内容</h1>
</div>
<div class="user">
<h1>用户页面</h1>
</div>
</div>
<script type="text/javascript">
const router = [
{path:"/" ,component:home},
{path:"/about" ,component:about},
{path:"/user" ,component:document.querySelector(".user")},
]
var currentView = router[0];
location.hash = "#"+currentView.path;
window.onhashchange=function(e){
var hash = window.location.hash.slice(1);
console.log(hash);
router.forEach((item,index)=>{
if(hash == item.path){
currentView.component.style.display = "none";
item.component.style.display="block";
currentView = router[index];
}
})
}
</script>
</body>
</html>