123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <!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>
- ul{
- margin: 0;
- padding: 0;
- display: flex;
- }
- li{
- list-style: none;
- width: 100px;
- height: 50px;
- background-color: #aaa;
- color: #fff;
- font-weight: bold;
- text-align: center;
- line-height: 50px;
- }
- .active{
- background-color: #000;
- }
- </style>
- </head>
- <body>
- <ul>
- <li data-hash="first" class="active">first</li>
- <li data-hash="second">second</li>
- <li data-hash="third">third</li>
- </ul>
- <script>
- let aLi = document.querySelectorAll("li");
- for(let i=0;i<aLi.length;i++){
- aLi[i].onclick = function(e){
- let thisVal = e.target.dataset.hash;
- // location.hash = thisVal;
- history.pushState(thisVal,"");
- for(let j=0;j<aLi.length;j++){
- aLi[j].classList.remove("active");
- }
- this.classList.add("active");
- }
- }
- window.onpopstate = function(e){
- console.log(e.state);
- for(let i=0;i<aLi.length;i++){
- if(aLi[i].dataset.hash == e.state){
- aLi[i].classList.add("active")
- }else{
- aLi[i].classList.remove("active");
- }
- }
-
- }
- </script>
- </body>
- </html>
|