fengchuanyu hace 10 horas
padre
commit
75fb968a81
Se han modificado 1 ficheros con 92 adiciones y 0 borrados
  1. 92 0
      6_HTML5/练习4_history历史管理.html

+ 92 - 0
6_HTML5/练习4_history历史管理.html

@@ -0,0 +1,92 @@
+<!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>