10-基础-路由-js 实现路由

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        * {
            padding: 0;
            margin: 0;
        }

        li {
            list-style: none;
            float: left;
            margin-left: 10px;
        }

        a {
            text-decoration: none;
        }
    </style>
</head>

<body>
    <!--  AAA  BBB CCC  DDD  -->
    <!-- 设置导航链接 -->
    <ul>
        <li><a href="#/AAA">AAA</a></li>
        <li><a href="#/BBB">BBB</a></li>
        <li><a href="#/CCC">CCC</a></li>
        <li><a href="#/DDD">DDD</a></li>
    </ul>
    <br>
    <!-- 容器 -->
    <div id="main"></div>

    <script>
        var div = document.getElementById("main");
        // 目的: 根据不同的标识 渲染不同内容
        // -> 获取当前的标识->判断->渲染内容
        // 获取#/AAA -> 获取浏览器事件  -> BOM事件 -> location (hash)
        window.onhashchange = function () {
            // 获取hash <- location
            // console.log(location);
            var hash = location.hash; // #/BBB
            hash = hash.replace("#/", "");

            console.log(hash);
            switch (hash) {
                case "AAA":
                    div.innerText = "AAAAAAAAA"
                    break;
                case "BBB":
                    div.innerText = "BBBBBBBBB"
                    break;
                case "CCC":
                    div.innerText = "CCCCCCCCC"
                    break;
                case "DDD":
                    div.innerText = "DDDDDDDDD"
                    break;
                default:
                    break;
            }
        }
    </script>
</body>

</html>

posted @ 2019-05-28 22:53  193557749  阅读(165)  评论(0编辑  收藏  举报