1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <!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>
- <!-- 添加自定义属性 data-index 来存储索引 -->
- <li data-index="0" class="active">first</li>
- <li data-index="1">second</li>
- <li data-index="2">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");
- //添加历史记录
- // 获取自定义属性 data-index的值
- var dataIndex = this.dataset.index;
- // 把索引存储到历史记录中
- history.pushState(dataIndex,"");
- }
- }
- // 第三步监听历史变化
- window.onpopstate = function(){
- var historyState = history.state;
- // 将获取的state值转换为数字
- historyState = parseInt(historyState);
- // 移除所有选中状态
- for(var j=0;j<aLi.length;j++){
- aLi[j].classList.remove("active");
- }
- // 控制对应li添加选中状态
- aLi[historyState].classList.add("active");
- }
- </script>
- </body>
- </html>
|