溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

html5中有哪些api

發(fā)布時(shí)間:2021-12-13 15:09:08 來(lái)源:億速云 閱讀:197 作者:小新 欄目:web開(kāi)發(fā)

這篇文章主要介紹了html5中有哪些api,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

html5的api有:1、requestAnimationFrame;2、客戶端存儲(chǔ);3、歷史記錄(History);4、worker;5、file Reader;6、websocoket等等。

本教程操作環(huán)境:windows7系統(tǒng)、HTML5版、Dell G3電腦。

一、requestAnimationFrame (請(qǐng)求動(dòng)畫(huà)關(guān)鍵幀)

1.1  requestAnimationFrame怎么使用?

鋪墊:

先看一下,我們平時(shí)在JS中是怎么讓一個(gè)元素產(chǎn)生動(dòng)畫(huà)效果的。

我們平時(shí)都是用定時(shí)器來(lái)設(shè)置多長(zhǎng)時(shí)間后發(fā)生什么動(dòng)畫(huà),或者位移

<style>
    .demo{
        width: 100px;
        height:100px;
        background-color: red;
        position:absolute;
        left: 0;
    }
    </style>
</head>
<body>
    <div class="demo"></div>
    <script>
    var dom = document.getElementsByClassName('demo')[0];
    items = setInterval(function(e){
        dom.style.left = dom.offsetLeft + 50 +'px';
        if(dom.offsetLeft == 500){
            clearInterval(items);
        }
    },10);
    </script>

html5中有哪些api

我們可以看到,用JS定時(shí)器就可以實(shí)現(xiàn)動(dòng)畫(huà)效果

但是,JS定時(shí)器會(huì)有一個(gè)缺點(diǎn)

html5中有哪些api

瀏覽器的重繪是每1s  ——》 60次,所以大約為16ms重繪一次

如果我們像上面執(zhí)行的一樣,每隔10ms就增加 left50px 。頁(yè)面就會(huì)造成關(guān)鍵幀丟失

html5中有哪些api

requestAnimationFrame:(優(yōu)化后)

<style>
        .demo {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="demo"></div>
    <script>
        var dom = document.getElementsByClassName('demo')[0];
        function move() {
            dom.style.left = dom.offsetLeft + 50 + 'px';
            var items = requestAnimationFrame(move);
            if(dom.offsetLeft == 500){
                cancelAnimationFrame(items);
            }
        }
        move();
    </script>

html5中有哪些api

1.2  requestAnimationFrame與setTImeout的區(qū)別?

setTimeout 是以 n 毫秒后執(zhí)行回調(diào)函數(shù),回調(diào)函數(shù)中可以遞歸 調(diào)用 setTimeout 來(lái)實(shí)現(xiàn)動(dòng)畫(huà)。

.demo {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="demo"></div>
    <script>
        var dom = document.getElementsByClassName('demo')[0];
        function move() {
            var items = setTimeout(function () {
                dom.style.left = dom.offsetLeft + 50 + 'px';
                if (dom.offsetLeft == 500) {
                    clearTimeout(items);
                } else {
                    move();
                }
            }, 10)
        }
        move();
    </script>

html5中有哪些api

使用 requestAnimationFrame 執(zhí)行動(dòng)畫(huà),最大優(yōu)勢(shì)是能保證回調(diào)函數(shù)在屏幕每一次刷 新間隔中只被執(zhí)行一次,這樣就不會(huì)引起丟幀,動(dòng)畫(huà)也就不會(huì)卡頓。

.demo {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="demo"></div>
    <script>
        var dom = document.getElementsByClassName('demo')[0];
        function move() {
            var items = requestAnimationFrame(function () {
                dom.style.left = dom.offsetLeft + 50 + 'px';
                if (dom.offsetLeft == 500) {
                    cancelAnimationFrame(items);
                } else {
                    move();
                }
            })
        }
        move();
    </script>

html5中有哪些api

1.3  requestAnimationFrame的優(yōu)勢(shì)

html5中有哪些api

二、客戶端存儲(chǔ)

2.1  Storage: 不會(huì)傳到服務(wù)器

2.1.1 Storage 如何使用  掌握方法

html5中有哪些api

存儲(chǔ)對(duì)象:

html5中有哪些api

html5中有哪些api

取出對(duì)象:

html5中有哪些api

儲(chǔ)存數(shù)組:

html5中有哪些api

html5中有哪些api

取出數(shù)組:

html5中有哪些api

API    localstorage sessionStorage  共同適用

html5中有哪些api

設(shè)置,獲得

html5中有哪些api

移除屬性(指定個(gè)別屬性)

html5中有哪些api

清除所有已設(shè)置的屬性

html5中有哪些api

2.1.2  localstorage sessionStorage cookie區(qū)別

localstorage:

  存儲(chǔ)信息到用戶的設(shè)備上,一般為5MB

  永久存儲(chǔ),除非手動(dòng)清除

  會(huì)存儲(chǔ)到同域下

sessionStorage:

  存儲(chǔ)信息到用戶的設(shè)備上,一般為5MB

  臨時(shí)存儲(chǔ),頁(yè)面關(guān)閉就會(huì)清除

  不會(huì)存儲(chǔ)到同域下

cookie:

  存儲(chǔ)信息到用戶的設(shè)備上,數(shù)據(jù)量較小  4k

  navigator.cookieEnabled  檢查是否啟用了cookie

html5中有哪些api

三、歷史記錄

BOM中的 History對(duì)象方法

現(xiàn)在已知我有三個(gè)標(biāo)簽頁(yè)(從紅色小方塊開(kāi)始)

html5中有哪些api

3.1history.length   長(zhǎng)度

通過(guò)調(diào)用這個(gè)方法就可以知道,當(dāng)前歷史記錄里面有幾條數(shù)據(jù)(幾個(gè)網(wǎng)頁(yè))

html5中有哪些api

3.1history.back()   回退

當(dāng)前位置在第三頁(yè)(淘寶頁(yè)面),回退一頁(yè)就會(huì)跳轉(zhuǎn)到第二頁(yè)(百度頁(yè)面)

html5中有哪些api

3.2 history.forward()   前進(jìn)

當(dāng)前在紅色小方塊當(dāng)前頁(yè),前進(jìn)一頁(yè)就會(huì)跳轉(zhuǎn)至第二頁(yè)(百度頁(yè)面)

html5中有哪些api

3.3 history.go(n)     跳轉(zhuǎn)至指定頁(yè)

當(dāng)前在紅色小方塊頁(yè)面即為第0頁(yè),go(2)就會(huì)跳轉(zhuǎn)至第三頁(yè)(淘寶頁(yè)面)

html5中有哪些api

當(dāng)前在淘寶頁(yè)面即為第三頁(yè),go(-2)就會(huì)跳轉(zhuǎn)至第一頁(yè)(紅色方塊頁(yè)面)

html5中有哪些api

HTML5中新增的方法   此方法受同源策略限制,需要在服務(wù)器下操作

html5中有哪些api

1、pushState   添加一條歷史記錄

html5中有哪些api

2、replaceState   替換當(dāng)前的歷史記錄

html5中有哪些api

html5中有哪些api

1.  popstate 監(jiān)聽(tīng)頁(yè)面歷史記錄一旦發(fā)生改變時(shí)觸發(fā)

        history.pushState(null, null, '#a');
        window.addEventListener('popstate', function(e){  //監(jiān)聽(tīng) popstate事件 有沒(méi)有發(fā)生改變 
            console.log("歷史記錄發(fā)生改變,我觸發(fā)了");
        }, false)

html5中有哪些api

應(yīng)用場(chǎng)景

多應(yīng)用于搜索,后臺(tái)管理系統(tǒng),或者父子頁(yè)面之間的切換(開(kāi)發(fā)一個(gè)頁(yè)面就夠了)

html5中有哪些api

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <input type="text" id="inp">
    <button id="btn">搜索</button>
    <ul id="wrapper"></ul>
    <script>
        var wrapper = document.getElementById('wrapper');
        var inp = document.getElementById('inp');
        var btn = document.getElementById('btn');
        var data = [{
            name: '科比'
        }, {
            name: '杜蘭特'
        }, {
            name: '庫(kù)里'
        }, {
            name: '哈登'
        }, {
            name: '詹姆斯'
        }, {
            name: '字母哥'
        }, {
            name: '杜蘭特'
        }, {
            name: '科比'
        }, {
            name: '科比'
        }];
        function radeDom(data) {  
            var str = " ";
            for (var i = 0; i < data.length; i++) {
                str += "<li>" + data[i].name + "</li>";
            }
            wrapper.innerHTML = str;
        }
        radeDom(data);

        btn.onclick = function () {
            var key = inp.value;
            var dataList = data.filter(function (item, index) {
                return item.name.indexOf(key) > -1;
            })
            radeDom(dataList);
            history.pushState({   //點(diǎn)擊后添加歷史記錄,key為當(dāng)前的key
                key: key
            }, null, '#a');
        }
        
        window.addEventListener('popstate', function (e) {  //當(dāng)歷史記錄事件改變時(shí)
            var key = e.state ? e.state.key : '';           //判斷當(dāng)前頁(yè)的key是否等于當(dāng)前頁(yè)的key
            var dataList = data.filter(function (item, index) {
                return item.name.indexOf(key) > -1;
            });
            inp.value = key;  //讓輸入框的value等于當(dāng)前頁(yè)的key
            radeDom(dataList);
        }, false)
    </script>
</body>
</html>

2.  hashchange

用于監(jiān)聽(tīng)hash值的改變觸發(fā)事件,就是鏈接 # 這個(gè)東西的改變而觸發(fā)

跟popstate的用法大同小異,都差不多。用途也都是一樣的。所以大家可以自己試試

四、worker  (受同源策略限制,需要在服務(wù)器下運(yùn)行)

4.1 了解worker

worker字面意思是工人、雇傭員工的意思。

worker是一種異步執(zhí)行JS的方式。

4.2 worker應(yīng)用

   var worker = new worker('worker.js');    
   // worker文件必須和主文件滿足同源策略

就是在執(zhí)行代碼前雇傭一名工人(一個(gè)JS文件),把數(shù)據(jù)交給他讓他異步執(zhí)行,執(zhí)行完了給主人返回回來(lái)。

主人可以在執(zhí)行完代碼后,調(diào)用解雇工人的方法,就不能繼續(xù)傳數(shù)據(jù),

工人可以在執(zhí)行完代碼后,調(diào)用辭職方法,就不能繼續(xù)傳數(shù)據(jù)。

傳輸數(shù)據(jù)

postMessage 、onmessage

html5中有哪些api

返回?cái)?shù)據(jù)

html5中有哪些api

4.3 結(jié)束worlker

html5中有哪些api

html5中有哪些api

html5中有哪些api

4.4woker的缺點(diǎn)

(1)同源限制

分配給 Worker 線程運(yùn)行的腳本文件,必須與主線程的腳本文件同源。

(2)DOM 限制

Worker 線程所在的全局對(duì)象,與主線程不一樣,無(wú)法讀取主線程所在網(wǎng)頁(yè)的 DOM 對(duì)象,也無(wú)法使用document、window、parent這些對(duì)象。但是,Worker 線程可以navigator對(duì)象和location對(duì)象。

(3)通信聯(lián)系

Worker 線程和主線程不在同一個(gè)上下文環(huán)境,它們不能直接通信,必須通過(guò)消息完成。

(4)腳本限制

Worker 線程不能執(zhí)行alert()方法和confirm()方法,但可以使用 XMLHttpRequest 對(duì)象發(fā)出 AJAX 請(qǐng)求。

(5)文件限制

Worker 線程無(wú)法讀取本地文件,即不能打開(kāi)本機(jī)的文件系統(tǒng)(file://),它所加載的腳本,必須來(lái)自網(wǎng)絡(luò)。

4.5 其他特性

html5中有哪些api

4.6主要應(yīng)用場(chǎng)景

Ajax輪詢可以使用,每隔一段時(shí)間獲取一下數(shù)據(jù)(用一個(gè)定時(shí)期每隔一段時(shí)間,向后端發(fā)送一次請(qǐng)求)

五、fileReader(上傳文件,讀取中的詳細(xì)信息)

5.1 fileReader的使用方法

var reader = new FileReader();

html5中有哪些api

 按照不同項(xiàng)目的需求使用不同的方法,在這里我們就用這里面的readAsDataURL( )這個(gè)方法

我們先來(lái)看怎么讀取文件,我們需要先把文件發(fā)送至服務(wù)器,等他給我返回文件的URL地址,然后我拿著URL地址來(lái)渲染我的頁(yè)面

html5中有哪些api

既然我們可以接收到返回的地址,那我們就可以把圖片渲染到頁(yè)面了

html5中有哪些api

<style>
    .img{
        height: 300px;
    }
    </style>
</head>
<body>
    <input type="file">
    <img src="" alt="" class="img">
    <script>
    var reader = new FileReader();   //創(chuàng)建FileReader(讀文件對(duì)象)
    var inp = document.getElementsByTagName('input')[0];
    var img = document.getElementsByClassName('img')[0];
    inp.onchange = function(){       //onchange是當(dāng)用戶改變input輸入框內(nèi)容時(shí)執(zhí)行一段JS代碼時(shí)觸發(fā)
        console.log(inp.files);      //flies 是你上傳什么文件,他就會(huì)給你返回一個(gè)文件信息的偽數(shù)組
        reader.readAsDataURL(inp.files[0]);//讀取文件,偽數(shù)組中的第0項(xiàng)
    }
    reader.onloadstart = function(e){
        console.log('讀取開(kāi)始時(shí)觸發(fā)', e);
    }
    reader.onprogress = function(e){
        console.log('讀取中', e);
    }
    reader.onloadend = function(e){
        console.log('讀取完成', e);
    }
    reader.onload = function(e){
        console.log('文件讀取成功', e);
    }
    reader.onabort = function(e){
        console.log('中斷時(shí)觸發(fā)', e);
    }
    reader.onerror = function(e){
        console.log('出錯(cuò)時(shí)觸發(fā)', e);
    }
    </script>

html5中有哪些api

<style>
    .img{
        height: 300px;
    }

    </style>
</head>
<body>
    <input type="file">
    <img src="" alt="" class="img">
    <script>
    var reader = new FileReader();   //創(chuàng)建FileReader(讀文件對(duì)象)
    var inp = document.getElementsByTagName('input')[0];
    var img = document.getElementsByClassName('img')[0];
    inp.onchange = function(){       //onchange是當(dāng)用戶改變input輸入框內(nèi)容時(shí)執(zhí)行一段JS代碼時(shí)觸發(fā)
        console.log(inp.files);      //flies 是你上傳什么文件,他就會(huì)給你返回一個(gè)文件信息的偽數(shù)組
        reader.readAsDataURL(inp.files[0]);//讀取文件,偽數(shù)組中的第0項(xiàng)
    }
    reader.onloadstart = function(e){
        console.log('讀取開(kāi)始時(shí)觸發(fā)', e);
    }
    reader.onprogress = function(e){
        console.log('讀取中', e);
    }
    reader.onloadend = function(e){
        console.log('讀取完成', e);
    }
    reader.onload = function(e){
        console.log('文件讀取成功', e);
        img.src = e.target.result;
    }
    reader.onabort = function(e){
        console.log('中斷時(shí)觸發(fā)', e);
    }
    reader.onerror = function(e){
        console.log('出錯(cuò)時(shí)觸發(fā)', e);
    }
    </script>

html5中有哪些api

 在文件讀取中我們可以知道兩個(gè)值  loaded、total

html5中有哪些api

已知這兩個(gè)值,我們就可以實(shí)現(xiàn)加載進(jìn)度條了

<style>
    .img{
        height: 300px;
    }
    .wrapper{
        width: 300px;
        height: 30px;
        border: 1px solid black;
    }
    .wrapper .content{
        width: 0;
        height: 30px;
        background-color:blue;
        overflow: hidden;
    }

    </style>
</head>
<body>
    <input type="file">
    <img src="" alt="" class="img">
    <div class="wrapper">
        <div class="content"></div>
    </div>
    <span class="text"></span>
    <script>
    var reader = new FileReader();   //創(chuàng)建FileReader(讀文件對(duì)象)
    var inp = document.getElementsByTagName('input')[0];
    var img = document.getElementsByClassName('img')[0];
    var con = document.getElementsByClassName('content')[0];
    var text = document.querySelector('.text');
    inp.onchange = function(){       //onchange是當(dāng)用戶改變input輸入框內(nèi)容時(shí)執(zhí)行一段JS代碼時(shí)觸發(fā)
        console.log(inp.files);      //flies 是你上傳什么文件,他就會(huì)給你返回一個(gè)文件信息的偽數(shù)組
        reader.readAsDataURL(inp.files[0]);//讀取文件,偽數(shù)組中的第0項(xiàng)
    }
    reader.onloadstart = function(e){
        console.log('讀取開(kāi)始時(shí)觸發(fā)', e);
    }
    reader.onprogress = function(e){
        // console.log('讀取中', e。loaded / e.total * 100%);
        var precent = e.loaded / e.total * 100;  //當(dāng)前讀取的值除以文件總大小,乘以100%。在讀取中會(huì)不斷觸發(fā)
        var width = Math.round(300 * precent / 100); //進(jìn)度條長(zhǎng)度300乘以前面得到的值,除以100%,四舍五入取整
        con.style.width = width + 'px'; //把值賦給寬度
        text.innerHTML = Math.round(precent) + '%'; //把讀取中的值取整把數(shù)字賦給文字進(jìn)度條
    }
    reader.onloadend = function(e){
        console.log('讀取完成', e);
    }
    reader.onload = function(e){
        console.log('文件讀取成功', e);
        img.src = e.target.result;
    }
    reader.onabort = function(e){
        console.log('中斷時(shí)觸發(fā)', e);
    }
    reader.onerror = function(e){
        console.log('出錯(cuò)時(shí)觸發(fā)', e);
    }
    </script>

html5中有哪些api

然后我們還可以添加終止讀取,就是在文件上傳的中途,停止上傳

只需要添加一個(gè)按鈕,和一個(gè)點(diǎn)擊事件

        btn.onclick = function () {
            reader.abort();
            console.log('終止');
        }

html5中有哪些api

5.2 fileReader 可實(shí)現(xiàn)的功能

圖片預(yù)覽、異步向發(fā)送服務(wù)端發(fā)送請(qǐng)求

六、websocket(不受同源策略限制)

websocket是一種網(wǎng)絡(luò)協(xié)議,是在HTTP基礎(chǔ)上做了一些優(yōu)化的協(xié)議,與HTTP無(wú)直接關(guān)系。

6.1  簡(jiǎn)單回憶HTTP協(xié)議

html5中有哪些api

6.2為什么有HTTP還需要websocket呢?

因?yàn)镠TTP協(xié)議有一個(gè)缺陷:通信只能由客戶端發(fā)起

服務(wù)器端不能實(shí)時(shí)的發(fā)送最新數(shù)據(jù)給客戶端,

我想要最新的數(shù)據(jù)怎么辦呢? 只能用Ajax輪詢(開(kāi)啟一個(gè)定時(shí)器,每隔一段時(shí)間調(diào)用請(qǐng)求一次數(shù)據(jù))

然而websocket呢只需要發(fā)送一次請(qǐng)求,只要服務(wù)器有最新數(shù)據(jù)就會(huì)自動(dòng)給你發(fā)送過(guò)來(lái),不用再次請(qǐng)求

比如現(xiàn)在做的是一個(gè)天氣狀況的項(xiàng)目,每當(dāng)天氣有變化就會(huì)自動(dòng)更新最新天氣狀況了

6.3 websocket的特點(diǎn)

html5中有哪些api

6.4 websocket事件

html5中有哪些api

6.5 創(chuàng)建websocket

ws://echo.websocket.org/    是用來(lái)測(cè)試的地址
    var socket = new WebSocket('ws://echo.websocket.org/');

html5中有哪些api

調(diào)用e.data就可以打印出來(lái)數(shù)據(jù)了

html5中有哪些api

我們?cè)賮?lái)看看close這個(gè)方法

html5中有哪些api

6.6 websocket屬性

html5中有哪些api

html5中有哪些api

6.7 websocket的優(yōu)點(diǎn)

客戶端與服務(wù)器都可以主動(dòng)傳送數(shù)據(jù)給對(duì)方;

不用頻率創(chuàng)建TCP請(qǐng)求及銷(xiāo)毀請(qǐng)求,減少網(wǎng)絡(luò)帶寬資源的占用,同時(shí)也節(jié)省服務(wù)器資源;

可以只請(qǐng)求一次,就會(huì)自動(dòng)更新返回

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“html5中有哪些api”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI