直接上代码
<p><a href="#/home">首页</a>|<a href="#/about">关于</a>|<a href="#/info">信息</a></p>
<div id="home">
<h1>首页</h1>
</div>
<div id="about">
<h1>关于</h1>
</div>
<div id="info">
<h1>信息</h1>
</div>
<style>
#about {
display: none;
}
#info {
display: none;
}
</style>
- 看一下页面效果
- 现在需要实现需求,点击关于页面显示关于,同时URL也显示对应的a标签href的内容

- 通过hashchange改变事件来实现这个需求
- hash就是页面上显示URL
- 一大堆if判断就是让对应的文字显示
- 没有用document.getElementById是因为,当元素为页面唯一元素的时候可以直接用
window.onhashchange = function (e) {
let hash = window.location.hash;
console.log(hash)
if (hash == '#/home') {
home.style.display = 'block';
about.style.display = 'none';
info.style.display = 'none';
} else if (hash == '#/about') {
home.style.display = 'none';
about.style.display = 'block';
info.style.display = 'none';
} else if (hash == '#/info') {
home.style.display = 'none';
about.style.display = 'none';
info.style.display = 'block';
}
}


Vue路由跳转(正戏)
- 是不是感觉很熟悉?
- 这就是vue的路由配置方式
- path是地址栏显示的URL
- component是需要显示对用的页面,在这里就是那几个div
const router = [
{path:'#/home',component:home},
{path:'#/about',component:about},
{path:'#/info',component:info}
]
let currentView = router[0];
window.onhashchange = function(e) {
for(let i = 0; i < router.length; i++) {
if(location.hash == router[i].path) {
currentView.component.style.display = 'none';
router[i].component.style.display = 'block';
currentView = router[i];
break;
}
}
}
