Code directly
- Write something on the page
<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>
- The first one is displayed by default, which is the homepage
<style>
#about {
display: none;
}
#info {
display: none;
}
</style>
- Take a look at the page effect
- Now you need to achieve the requirements, clickonThe page shows about and at the same timeURLAlso display the corresponding a taghrefContent
- byhashchangeChange events to fulfill this requirement
- hashIs the URL displayed on the page
- A lotifJudgment is to let the corresponding text display
- Document.getElementById is not used because it can be used directly when the element is the only element on the page
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';
}
}
- Take a look at the printedhash
- Take a look at the page effect
Vue routing jump (positive play)
- Does it feel familiar?
- This is how vue is configured for routing
- pathIs displayed in the address barURL
- componentNeed to be displayedpage, Here are those divs
const router = [
{
path:'#/home',component:home},
{
path:'#/about',component:about},
{
path:'#/info',component:info}
]
- The corresponding js code
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;
}
}
}
- See if the effect is the same