1. 程式人生 > 其它 >spa應用的簡單實現-錨點

spa應用的簡單實現-錨點

<!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>
        li {
            list
-style: none; } a { text-decoration: none; } .selected { color: red; background-color: darkgrey; } </style> </head> <body> <ul> <li><a href="#/home">首頁</a></li> <li><a href="
#/news">新聞</a></li> <li><a href="#/joinin">招聘</a></li> </ul> <hr/> <p></p> <script> var pObj = document.querySelector("p"); var homeObj = document.querySelector("a[href='#/home']"); var newsObj = document.querySelector("
a[href='#/news']"); var joininObj = document.querySelector("a[href='#/joinin']"); var aryObj = [homeObj, newsObj, joininObj]; window.onhashchange = () => { changeElements(location.hash.substr(2), aryObj, pObj); } function changeElements(hash, aryObj, pObj) { let text = hash === 'home' ? "首頁" : hash === 'news' ? "新聞" : "招聘"; let selectedIndex = hash === 'home' ? 0 : hash === 'news' ? 1 : 2; aryObj.forEach((val, index) => { val.className = selectedIndex === index ? "selected" : ""; }); pObj.innerText = "歡迎來到【" + text + "】頁面."; } </script> </body> </html>