| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <!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;
- margin:100px auto;
- }
- .box ul{
- display: flex;
- }
- .box li{
- width: 200px;
- height: 100px;
- background-color: #aaa;
- font-size: 50px;
- line-height: 100px;
- text-align: center;
- color: #fff;
- }
- .box .active{
- background-color: #111;
- }
- </style>
- </head>
- <body>
- <div class="box">
- <ul>
- <li class="active" data-id="first">first</li>
- <li data-id="second">second</li>
- <li data-id="third">third</li>
- </ul>
- </div>
- <script>
- var aLi = document.querySelectorAll("li");
- //定义函数处理选中状态
- function handleActive(key){
-
- for(var i=0;i<aLi.length;i++){
- if(aLi[i].dataset.id == key){
- aLi[i].classList.add("active");
- }else{
- aLi[i].classList.remove("active");
- }
-
- }
-
- }
- // 绑定标签按钮点击事件
- for(var i=0;i<aLi.length;i++){
- aLi[i].onclick = function(){
- var _id = this.dataset.id;
- // 调用处理选中状态函数
- handleActive(_id);
- // 添加历史记录
- history.pushState(_id,"");
- }
- }
- // 监听history变化
- window.onpopstate = function(event){
- var _state = event.state;
- console.log(_state);
- // 调用处理选中状态函数
- // handleActive(_state);
- if(_state){
- handleActive(_state);
- }else{
- handleActive(aLi[0].dataset.id);
- }
- }
- </script>
- </body>
- </html>
|