<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单页hash跳转</title>
</head>
<body>
<script>
window.addEventListener("DOMContentLoaded", function(){
//DOM树构建完成后执行下面的代码
function router(option){
var hash = location.hash.slice(1) || "/";
option[hash]();
}
function on(events,callback){
var ev = events.split(' ');
for(var i in ev){
window.addEventListener(ev[i],callback)
}
}
var content = document.querySelector('.content');
// 刷新文档 或hash改变的时候调用 router 函数
on('load hashchange',function(){router({
"/":function(){
content.innerHTML = "home";
},
"/about":function(){
content.innerHTML = "about us";
},
"/news":function(){
content.innerHTML = "news";
},
"/product":function(){
content.innerHTML = "product";
}
})
})
})
</script>
<div class="container">
<nav class="nav">
<a href="#/">home</a>
<a href="#/news">news</a>
<a href="#/product">product</a>
<a href="#/about">about us</a>
</nav>
<div class="content">
</div>
</div>
<style>
.container{
width: 960px;
min-height: 400px;
background: #eee;
margin: 0 auto;
border-radius: 15px;
overflow: hidden;
}
.nav{
width: 100%;
height: 80px;
line-height: 80px;
background: #ccc;
text-align: center;
}
.nav a{
margin:0 20px;
}
.content{
text-align: center;
font-size: 60px;
font-weight: bold;
padding: 50px;
}
</style>
</body>
</html>
单页 hash 跳转
最新推荐文章于 2023-10-30 21:13:29 发布