HTML5新特性

HTML5

一個最簡單的html5頁面模版以下:javascript

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>

<body>
Content of the document......
</body>

</html>

 


 

HTML5新元素

  1. 新增的語義化的標籤:<header>, <footer>, <article>, and <section......
  2. 新的元素屬性:number, date, time, calendar, and range......
  3. 新的繪圖元素:<svg> and <canvas>
  4. 新的多媒體元素:<audio> and <video>

 

HTML5新API

  • HTML Geolocation
  • HTML Drag and Drop
  • HTML Local Storage
  • HTML Application Cache
  • HTML Web Workers
  • HTML SSE

 

語義化的標籤

什麼是語義化的標籤?php

一個語義化的元素清楚地描述了它對瀏覽器和開發者的意義。html

無語義化的元素:<div>,<span>和其所包含的內容並無關係。html5

語義化的元素:<form>, <table>,<article>清楚的定義了其所包含的內容。java

 

爲何提倡使用語義化的標籤?git

在HTML4時代,開發者們使用本身的id選擇器或者類名選擇器來定義元素的樣式,這使得搜索引擎沒法正確識別網頁內容。
web

經過使用HTML5提供的語義化的標籤元素,搜索引擎能夠更加簡單的識別網頁內容。canvas

According to the W3C, a Semantic Web: "Allows data to be shared and reused across applications, enterprises, and communities."

 

HTML5新增的語義化標籤連接:瀏覽器

https://www.w3schools.com/html/html5_semantic_elements.asp


 

HTML5 Canvas

什麼是Canvas?服務器

Canvas是HTML5新增的一個用於繪圖的元素,Canvas使用JavaScript來繪製圖像。

 

Canvas參考連接:

https://www.w3schools.com/graphics/canvas_intro.asp

 


 

HTML5 SVG

What is SVG?

  • SVG stands for Scalable Vector Graphics
  • SVG is used to define graphics for the Web
  • SVG is a W3C recommendation

SVG參考連接:

https://www.w3schools.com/graphics/svg_intro.asp


Differences Between SVG and Canvas

SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with a JavaScript).

SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.

 

Comparison of Canvas and SVG

The table below shows some important differences between Canvas and SVG:

Canvas SVG
  • Resolution dependent
  • No support for event handlers
  • Poor text rendering capabilities
  • You can save the resulting image as .png or .jpg
  • Well suited for graphic-intensive games
  • Resolution independent
  • Support for event handlers
  • Best suited for applications with large rendering areas (Google Maps)
  • Slow rendering if complex (anything that uses the DOM a lot will be slow)
  • Not suited for game applications

 


 

HTML5多媒體元素:<video>和<audio> 

1.<video>

在video出現以前,要在網頁上播放視頻,必需要安裝相應的插件(like  flash),<video>定義了一套標準的方法來解決這個問題。

一個簡單的<video>的使用例子以下:

<video width="320" height="240" controls autoplay>
    <source src="青鳥.mp4" type="video/mp4">
    <source src="青鳥.ogg" type="video/ogg">
    Your browser does not support the video tag.
</video>

咱們定義了一個<video>標籤,標籤裏邊包含的<source>標籤是用來指定要播放的文件的路徑和類型,瀏覽器會使用第一個支持的文件類型,若是全部的文件類型都不支持,就會顯示文字提示。

這在Google瀏覽器當中顯示以下:

來分析一下<video>的屬性做用:

  1. controls:控制欄(也就是底部的播放/暫停按鈕,進度條,音量,全屏)是否顯示
  2. autoplay:是否自動播放

 

固然,常常上網看視頻的咱們也會發現,許多網站的播放器和上面原生的不太同樣呀?

其實video也提供了許多接口給開發者使用,經過這些接口能夠自定義本身的video樣式。

  1. play():開始播放視頻,經過play()和pause()能夠自定義播放按鈕。
  2. pause():暫停播放視頻。
  3. load():從新播放視頻。
  4. currentTime:返回或者設置當前的播放進度,經過currentTime和duration能夠自定義進度條。
  5. duration:返回視頻時長。
  6. volume:返回或者設置當前音量,經過這個屬性能夠自定義音量控件。
  7. playbackRate:設置或者返回當前的播放速率,經過這個屬性能夠控制播放速度

以上是一些經常使用的方法和屬性,詳細請參考:

https://www.w3schools.com/tags/ref_av_dom.asp

2.<audio>

audio用法與video相似

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

  

其API與video如出一轍


 

 HTML5新API

1.HTML Geolocation

此API能夠用來獲取用戶的地理位置,用法以下:

 (function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position, error) {
                console.log(position)
            });
        } else {
            console.log("Geolocation is not supported by this browser.")
        }
    })();

 首先檢查瀏覽器是否支持navigator.geolocation,該對象有一個getCurrentPosition函數,此函數接受一個回調函數做爲參數,

此回調函數的參數有兩個,第一個爲獲取的地理位置信息,第二個爲錯誤類型

咱們看一下控制檯的打印信息:

返回了一個Position對象:

Property Returns
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)

 

2.HTML Drag and Drop

一個例子

<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69">

</body>
</html>

首先,要知道不是全部的元素均可以被拖動,要使一個元素能夠被拖動,須要設置其

draggable="true"

,這樣元素就能夠被拖動了。

其次,並非全部的位置均可以drop,ondragOver指定那些位置能夠drop。

咱們還須要阻止默認的ondragOver事件

function allowDrop(ev) {
    ev.preventDefault();
}

 ondrop會在元素被釋放後觸發。

 相信平時咱們上網時也會接觸到一種新奇的場景——文件拖拽上傳,那麼這是如何實現的呢?demo以下:

http://luyufeng.wang/demos/HTML5%E6%8B%96%E6%8B%BD%E4%B8%8A%E4%BC%A0/

其中最重要的是dataTransfer.files屬性,這是一個FileList對象,上傳文件的信息全在這裏。

接着就可使用HTML5的FileReader()對象作進一步處理,FileReader()對象的初步使用能夠參考:

http://www.cnblogs.com/txwslyf/p/7249872.html

 

3.HTML Local Storage

  1. 要使用localStorage,第一步須要判斷瀏覽器是否支持localStorage:
    if(!window.localStorage){
                alert("瀏覽器不支持localstorage");
                return false;
            }else{
                //主邏輯業務
            }
    

      

  2. 第二步須要判斷所須要存儲的localStorage是否已經存在:
    if (!window.localStorage) {
            alert("瀏覽器支持localstorage");
            return false;
        }
        else {
            if (!window.localStorage.recipes) {
                window.localStorage.setItem('recipes', '[]');
            else
                {
                    //主邏輯業務
                }
    
            }
        }
    

      

  3. localStorage經常使用的幾種方法:
    • 保存一個鍵值對:localStorage.setItem('key', 'value')
    • 刪除一個鍵值對:localStorage.removeItem('key', 'value')
    • 獲取一個鍵值對:localStorage.getItem('key')
    • 刪除全部的localStorage:localStorage.clear()
    • 獲取全部的localStorage的鍵值:
      var storage=window.localStorage;
                  storage.a=1;
                  storage.setItem("c",3);
                  for(var i=0;i<storage.length;i++){
                      var key=storage.key(i);
                      console.log(key);
                  }
      

        

 localStorage只能夠儲存String類型的值,因此使用時通常是採用JSON格式的數據。

 

4.HTML Web Workers

看下面代碼:

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;

function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
    }
}

function stopWorker() { 
    w.terminate();
    w = undefined;
}
</script>

</body>
</html>

其中"demo_workers.js"文件內容以下:

var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page。

 

5.HTML SSE

SSE(Server-Sent Events),容許web頁面響應服務器觸發的事件。

看下面一段代碼:

<!DOCTYPE html>
<html>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>//檢驗當前瀏覽器是否支持SSE
if(typeof(EventSource) !== "undefined") {//指定服務器腳本位置
    var source = new EventSource("demo_sse.php");//建立回調函數,指定得到服務器數據以後所要作的事
    source.onmessage = function(event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>
相關文章
相關標籤/搜索