| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <!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;
- }
- .box{
- width: 600px;
- height: 100px;
- background-color: #999;
- margin:100px auto;
- }
- .box ul{
- display: flex;
- }
- .box li{
- width: 200px;
- height: 100px;
- font-size: 50px;
- font-weight: bold;
- text-align: center;
- line-height: 100px;
- color: white;
- }
- .box ul .active{
- background-color: #111;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <ul>
- <li class="active">first</li>
- <li>second</li>
- <li>thrid</li>
- </ul>
- </div>
- <script>
- var lis = document.querySelectorAll("li");
- // 循环绑定事件
- for(var i=0;i<lis.length;i++){
- lis[i].onclick = function(){
- // 点击li时,移除所有active类名
- for(var j=0;j<lis.length;j++){
- lis[j].classList.remove("active");
- }
- // 点击li时,为当前li添加active类名
- this.classList.add("active");
- // 使用hash模式添加历史记录
- location.hash = this.innerText;
- }
- }
- // 监听hashchange事件
- window.onhashchange = function(){
- // 获取当前hash值
- var hash = location.hash;
- // 截取字符串#后面的内容
- hash = hash.substring(1);
- console.log(hash);
- // 根据hash值,切换active类名
- for(var i=0;i<lis.length;i++){
- if(lis[i].innerText == hash){
- lis[i].classList.add("active");
- }else{
- lis[i].classList.remove("active");
- }
- }
- }
- </script>
- </body>
- </html>
|