1. 程式人生 > 其它 >HTML5-5【history、worker】

HTML5-5【history、worker】

技術標籤:HTML5jshtml5htmlcss

一.history

(1).history基礎

history.back()等同於瀏覽器的後退按鈕

history.forward()為前進,但是如果前進到頭了則不會有反應,後退也是

history.go(-1)也可以進行後退

history.go(1)可以進行前進

history.length可以列印history棧的長度

(2).replaceState

history.replaceState('this is a test',null,'test')此時瀏覽器地址後面會變為/test

第三個引數是用來設定url的

第二個引數是用來設定網頁條目名稱但是很多瀏覽器不支援了一般設定為null

第一個引數是狀態物件名稱

只會更改替換條目,並不會增加history棧長度

(3).pushState

history.pushState("pushState",null,"pushState.html")

瀏覽器不會檢查pushState.html是否存在,會直接替換。

通過history.state可以檢視到狀態物件名稱

第一個引數 state object

第二個引數 title

第三個引數 url 不會立馬載入頁面 會在重新訪問時載入頁面,新的url必需和舊的是同源的,否則會報錯

會增加history棧長度

(4).示例

點選切換放大

<!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>
        .container{
            width: 800px;
            height: 200px;
        }
        .box{
            float: left;
            width: 150px;
            height: 150px;
            margin: 20px;
            color: #fff;
            font-size: 30px;
            font-weight: bold;
            text-align: center;
            line-height: 150px;
            cursor: pointer;
            transition:  1s;
        }
        .red{
            background-color: red;
            border: 5px solid red;
        }
        .green{
            background-color: green;
            border: 5px solid green;
        }
        .blue{
            background-color: blue;
            border: 5px solid blue;
        }
        .black{
            background-color: black;
            border: 5px solid black;
        }
        .box:hover{
            background-color: #fff;
            color: #000;
        }
        .box.selected{
            transform: scale(1.2);
        }
    </style>
</head>
<body>
   <div class="container">
       <div class="box red selected" id="box-1">one</div>
       <div class="box green " id="box-2">two</div>
       <div class="box blue" id="box-3">three</div>
       <div class="box black" id="box-4">four</div>
   </div>
    <script>
     let boxes = Array.from(document.getElementsByClassName('box'));
     function selectBox(id){
         boxes.forEach(item => {
             item.classList.toggle('selected',item.id === id);
         })
     }
     boxes.forEach(item =>{
         item.addEventListener('click',e=>{
             let id = item.id;
             history.pushState({id},null,`selected=${id}`);
             selectBox(id)
         })
     })
    </script>
</body>
</html>

以上就完成了點選盒子放大然後url進行變更

popstate事件後退

現在要通過popState來完成點選前進後退之前對應的盒子也放大

在每一次活動的歷史條目發生改變的時候就會觸發,新增的話(push.replace)是不會觸發的

可以通過e,state會打印出棧設定的id

 window.addEventListener('popstate',e=>{
         let id = e.state.id;
         selectBox(id)
     })

這樣就實現了後退放大

(5).示例2

過濾

<body>
   <input type="text" id="inputKwd"/>
   <button id="btn">提交</button>
   <div class="output"></div>
    <script>
        let data = [
            {name:'VueJs'},
            {name:'ReactJs'},
            {name:'AngularJs'},
            {name:'jQuery'},
            {name:'HTML'},
            {name:'CSS'}
        ]
        let outputArea = document.getElementsByClassName('output')[0],
            btn = document.getElementById('btn'),
            inputKwd = document.getElementById('inputKwd');
        btn.addEventListener('click',()=>{
            let showData = data.filter(item=>{
                return item.name.indexOf(inputKwd.value) !== -1;
            })
            renderDom(showData)
            history.pushState({value:inputKwd.value},null,'#'+inputKwd.value)
        })    
        function renderDom(data){
            let outputStr = '';
            for (let i = 0; i < data.length; i++) {
                outputStr += '<p>'+data[i].name+'</p>'
                outputArea.innerHTML = outputStr
                
            }
        }
        renderDom(data)
    </script>
</body>

點選後退按鈕返回之前的查詢結果

 window.addEventListener('popstate',e=>{
            let value = e.state ? e.state.value :'';
            let showData = data.filter(item=>{
                return item.name.indexOf(value) !== -1;
            })
            inputKwd.value = value;
            renderDom(showData);
        },false)

(6).hashchange事件

hash變化時響應

點選a標籤上方文字變化

<body>
   <div>
       <p id="slot">...</p>
       <a href="#login">login</a>
       <a href="#logout">logout</a>
   </div>
    <script>
       let slot = document.getElementsByTagName('p')[0];
       window.addEventListener('hashchange',e=>ouRouterChange(e))
       function ouRouterChange(e){
           const hashLocation = window.location.hash.substring(1);
           loadingContent(hashLocation);
       }
       function loadingContent(uri){
           const contentUri = `${uri}.html`;
           fetch(contentUri).then(r =>t.text()).then(content => updateSlot(content));
       }
       function updateSlot(content){
           slot.innerHTML = content;
       }
    </script>
</body>

建立login.html

<h2>login.html</h2>

建立loginout.html

二.worker

(1).使用方式

產生分離指令碼,不影響頁面更新

postMessage()發出

onMessage()發出

worker.js(無法訪問window和document,可以寫ajax請求)

(2).具體例項

worker.js

this.onmessage=(e)=>{
    if(e.data.addThis !==undefined){
        let sumMessage = {result:e.data.addThis.num1+e.data.addThis.num2}
        this.postMessage(sumMessage)
    }
}

index.js

 <script>
      if(window.Worker){
          let myWorker = new Worker('worker.js')
          let message = {addThis:{num1:1,num2:3}}
          myWorker.postMessage(message);
          myWorker.onmessage=(e)=>{
              console.log(e.data.result);
          }
      }
    </script>

可以在worker中繼續委派worker

這樣的方式引入

importScripts('。。')

終止worker

myWorker.terminate();

這樣就無法通訊了