? ? ? ? 在之前整理BOM的五个对象时,提到:
? ? ? ? 本篇通过举例方式详细描述实现的过程。
注:根据hash值变化渲染组件,不会影响hash原有作为锚点的功能(锚点功能:根据#后面字符串滚动到对应id的元素 )
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hash Router</title>
</head>
<body>
<a href="#/user">Go user</a>
<a href="#/info">Go info</a>
<div id="root"></div>
<!-- <div style="height: 600px;"></div>
<div id="/info"></div> -->
<script>
let root = document.getElementById('root');
window.onhashchange = function(event) {
if(window.location.hash === '#/user') {
root.innerHTML = `
<label>
用户名:
<input value="小明" placeholder="user name"/>
</label>
`;
} else {
root.innerHTML = `
<label>
年龄:13岁
</label>
`;
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hash Router</title>
</head>
<body>
<div id="root"></div>
<script>
let root = document.getElementById('root');
window.onpushstate = function(state, title, url) {
console.dir({
type: 'onpushstate',
state,
pathname: url
});
render(url);
}
// 修改history.pushState方法,将window.onpushstate事件绑入
bindPushstate(window.history);
function bindPushstate(history) {
let pushState = history.pushState;
history.pushState = function(state, title, url) {
if(typeof window.onpushstate === 'function') {
window.onpushstate(state, title, url);
}
return pushState.apply(history, arguments);
}
}
window.onpopstate = function(event) {
const pathname = window.location.pathname;
console.dir({
type: event.type,
state: event.state,
pathname
});
render(pathname);
}
function render(pathname) {
if(pathname === '/user') {
root.innerHTML = `
<label>
用户名:
<input value="小明" placeholder="user name"/>
</label>
`;
} else if(pathname === '/info') {
root.innerHTML = `
<label>
年龄:13岁
</label>
`;
} else {
root.innerHTML = `
<label>
需要填写个人信息
</label>
`;
}
}
setTimeout(() => {
window.history.pushState({ page: 1 }, 'user', '/user');
}, 2000);
setTimeout(() => {
window.history.pushState({ page: 2 }, 'info', '/info');
}, 4000);
setTimeout(() => {
window.history.pushState({ page: 3 }, 'help', '/help');
}, 6000);
</script>
</body>
</html>
????????再牛的建筑都离不开一块一块砖瓦,学到很多高大上的框架和上层API时,再回过头来看基础,会更加深对框架和上层API的理解。
注:以上,如有不合理之处,还请帮忙指出,大家一起交流学习~??