代码改变世界

JS # hash

2021-12-05 19:52  qgbo  阅读(90)  评论(0)    收藏  举报
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <style>
        .flex-box{
            display: flex;height: 100px;
        }
        .center{
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
             border: 1px solid #ccc;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <div class="flex-box">
        <span class="flex1 center route">home</span>
        <span class="flex1 center route">shop</span>
        <span class="flex1 center route">shopcar</span>
        <span class="flex1 center route">usercenter</span>
    </div>
    <div id="root"></div>
</body>
<script>
    const routes = [{
        path:'/0',
        template:'<div>00000000AA</div>'
    },{
        path:'/1',
        template:'<div>11111111BB</div>'
    },{
        path:'/2',
        template:'<div>22222222CC</div>'
    },{
        path:'/3',
        template:'<div>33333333DD</div>'
    }]

var list = document.getElementsByClassName('route');
for (let i in list) {
list[i].onclick
= ()=> window.location.hash =/<span style="color: #000000;">${i};
}

window.addEventListener('hashchange',function(e){
var path = e.newURL.split('#')[1];
document.getElementById(
'root').innerHTML = routes.find(item=> item.path == path).template;
})
</script>
</html>