单页面开发路由原理

单页面开发路由原理

主要通过window.onhashchange监测路由hash值变化,触发事件。

代码

css

<style>
* {
    margin: 0;
    padding: 0;
}
#app>div {
    display: none;
}
</style>

html

<body>
    <div id="app">
        <div id="one">
            <h2>我是页面一</h2>
            <button type="button" onclick="location.hash='#tow'">去页面二</button>
            <button type="button" onclick="location.hash='#three'">去页面三</button>
        </div>
        <div id="tow">
            <h2>我是页面二</h2>
            <button type="button" onclick="location.hash='#one'">去页面一</button>
            <button type="button" onclick="location.hash='#three'">去页面三</button>
        </div>
        <div id="three">
            <h2>我是页面三</h2>
            <button type="button" onclick="location.hash='#one'">去页面一</button>
            <button type="button" onclick="location.hash='#tow'">去页面二</button>
        </div>
    </div>
</body>

js

<script>
    
    window.onhashchange = function(event) {
        // 获取路由hash值,该值与id相同,方便通过querySelector进行操作
        let hash = location.hash  
        // 将#app下的所有元素进行隐藏
        document.querySelectorAll("#app>*").forEach(item => {
            item.style.display = "none";
        })
        // 将hash值与id值相同的元素进行展示
        document.querySelector(hash).style.display = "block";
    }

</script>
上一篇:05dom


下一篇:获取页面元素的方法