12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- * {
- margin: 0;
- padding: 0;
- }
- li {
- list-style: none;
- }
- ul {
- display: flex;
- }
- li {
- width: 200px;
- height: 100px;
- color: white;
- background-color: gray;
- line-height: 100px;
- text-align: center;
- font-size: 40px;
- font-weight: bold;
- }
- .active {
- background-color: black;
- }
- </style>
- </head>
- <body>
- <!-- 第一步实现样式 -->
- <div>
- <ul>
- <li class="active">first</li>
- <li>second</li>
- <li>third</li>
- </ul>
- </div>
- <script>
- // 第二步绑定事件
- // 获取元素
- var aLi = document.querySelectorAll("li");
- // 循环绑定事件
- for (var i = 0; i < aLi.length; i++) {
- aLi[i].onclick = function () {
- // 移除所有选中状态
- for (var j = 0; j < aLi.length; j++) {
- aLi[j].classList.remove("active");
- }
- // 添加类名
- this.classList.add("active");
- // 修改hash值增加历史记录
- location.hash = this.innerText;
- }
- }
- // 第三步监听hash值变化
- window.onhashchange = function () {
- // 获取hash值
- var hash = location.hash;
- // 去掉#
- hash = hash.substr(1);
- // 移除所有选中状态
- for (var j = 0; j < aLi.length; j++) {
- aLi[j].classList.remove("active");
- }
- // 循环查找对应的hash值
- for (var i = 0; i < aLi.length; i++) {
- if (hash == aLi[i].innerText) {
- // 添加类名
- aLi[i].classList.add("active");
- }
- }
- }
- </script>
- </body>
- </html>
|