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>