你可能不知道的10個HTML5新功能

jopen 9年前發布 | 16K 次閱讀 HTML5

Element.classList

classList API提供了我們多年來一種使用JavaScript工具庫來實現的控制CSS的基本功能:

// 增加一個CSS類
myElement.classList.add("newClass");

// 刪除一個CSS類
myElement.classList.remove("existingClass");

// 檢查是否擁有一個CSS類
myElement.classList.contains("oneClass");

// 反轉一個CSS類的有無
myElement.classList.toggle("anotherClass");

這個新出現的API的主要價值體現就是:簡單實用。讀一下這篇文章,里面介紹了其它幾個classList功能特征。

ContextMenu API

這個新的ContextMenu API非常的有用:它并不會替換原有的右鍵菜單,而是將你的自定義右鍵菜單添加到瀏覽器的右鍵菜單里:

<section contextmenu="mymenu">

  <!-- 添加菜單 -->
  <menu type="context" id="mymenu">
      <menuitem label="Refresh Post" onclick="window.location.reload();" icon="/images/refresh-icon.png"></menuitem>
      <menu label="Share on..." icon="/images/share_icon.gif">
        <menuitem label="推ter" icon="/images/推ter_icon.gif" onclick="goTo('//推ter.com/intent/tweet?text=' + document.title + ':  ' + window.location.href);"></menuitem>
        <menuitem label="非死book" icon="/images/非死book_icon16x16.gif" onclick="goTo('//非死book.com/sharer/sharer.php?u=' + window.location.href);"></menuitem>
      </menu>
    </menu>
</section>

需要注意的是,最好使用JavaScript動態的創建這些菜單代碼,因為菜單事件最終要調用JavaScript執行任務,如果用戶禁止了JavaScript,右鍵菜單也不會生成,他同時也不會看到菜單。

Element.dataset

使用dataset API,程序員可以方便的獲取或設置data-*自定義屬性:

// 從A域上的窗口或iframe,發送一條信息到B域中的窗口或ifame
var iframeWindow = document.getElementById("iframe").contentWindow;
iframeWindow.postMessage("來自第一個窗口的問候!");

// 在第二個不同域上的窗口或iframe接收消息
window.addEventListener("message", function(event) {
    // 檢驗域的合法性
    if(event.origin == "http://www.webhek.com") {
        // 輸出日志信息
        console.log(event.data);

        // 反饋消息
        event.source.postMessage("你也好嗎!");
    }
]);

無需多說,跟classList一樣,簡單實用

window.postMessage API

即使是IE8也對postMessage API支持多年了,postMessage API的功能是可以讓你在兩個瀏覽器窗口或iframe之間傳遞信息數據:

/*  以下面的代碼為例

    <div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="This is the value"></div>

*/

// 獲取元素
var element = document.getElementById("myDiv");

// 獲取id
var id = element.dataset.id;

// 讀取 "data-my-custom-key" 的值
var customKey = element.dataset.myCustomKey;

// 修改成其它值
element.dataset.myCustomKey = "Some other value";

    // 結果是:
    //    <div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="Some other value"></div>

消息體只能是字符串,但你可以用JSON.stringify和JSON.parse將消息轉換成更有意義的數據體!

autofocus屬性

autofocus屬性能夠讓BUTTON, INPUT, 或 TEXTAREA元素在頁面加載完成時自動成為頁面焦點:

<input autofocus="autofocus" />
<button autofocus="autofocus">Hi!</button>
<textarea autofocus="autofocus"></textarea>

在像谷歌搜索頁面那樣的有固定模式的地方,autofocus屬性是最理想的一個功能。

瀏覽器對各個API的支持稍有不同,所以,在使用前先檢查一下對這些特征的支持情況。再花點時間閱讀一下各個API的詳細說明,相信你會有更多的發現。

全屏API接口

強大的全屏API接口能讓程序員通過編程啟動瀏覽器進入全屏模式,并請求用戶的允許:

// Find the right method, call on correct element
function launchFullScreen(element) {
  if(element.requestFullScreen) {
    element.requestFullScreen();
  } else if(element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if(element.webkitRequestFullScreen) {
    element.webkitRequestFullScreen();
  }
}

// Launch fullscreen for browsers that support it!
launchFullScreen(document.documentElement); // the whole page
launchFullScreen(document.getElementById("videoElement")); // any individual element


任何頁面元素都可以成為全屏輸出的目標,HTML5里甚至還提供了一個CSS偽類來讓程序員在瀏覽器全屏時控制全屏元素的樣式。當你在開發游戲時這個全屏API接口特別有用;尤其像BananaBread這樣的槍擊游戲中。

閱讀教程

頁面可見性API接口

頁面可見性API接口提供給用了一個監聽事件,這個事件能告訴程序員當前頁面是否是用瀏覽器中激活的標簽頁/窗口、是否是用戶正在觀看的頁面,它還能告訴程序員用戶何時切換頁面、不再觀看本頁面/窗口:

// Adapted slightly from Sam Dutton
// Set name of hidden property and visibility change event
// since some browsers only offer vendor-prefixed support
var hidden, state, visibilityChange; 
if (typeof document.hidden !== "undefined") {
  hidden = "hidden";
  visibilityChange = "visibilitychange";
  state = "visibilityState";
} else if (typeof document.mozHidden !== "undefined") {
  hidden = "mozHidden";
  visibilityChange = "mozvisibilitychange";
  state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
  state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
  state = "webkitVisibilityState";
}

// Add a listener that constantly changes the title
document.addEventListener(visibilityChange, function(e) {
  // Start or stop processing depending on state

}, false);

閱讀教程
觀看演示

getUserMedia接口API

getUserMedia API是個非常有趣的接口!使用這個API,加上<video>和<canvas>標記,你可以在瀏覽器里進行拍照!

// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
  // Grab elements, create settings, etc.
  var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    video = document.getElementById("video"),
    videoObj = { "video": true },
    errBack = function(error) {
      console.log("Video capture error: ", error.code); 
    };

  // Put video listeners into place
  if(navigator.getUserMedia) { // Standard
    navigator.getUserMedia(videoObj, function(stream) {
      video.src = stream;
      video.play();
    }, errBack);
  } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
    navigator.webkitGetUserMedia(videoObj, function(stream){
      video.src = window.webkitURL.createObjectURL(stream);
      video.play();
    }, errBack);
  }
}, false);

你一定要在以后的應用中試試這個HTML5新功能,通過瀏覽器進行各種各樣的交互的技術已經越來越流行了!

閱讀教程
觀看演示

電池接口API

電池接口API很顯然是專門為手機里的瀏覽器應用設計的,它提供了讀取設備里的電池電量和充電狀態的功能:

// Get the battery!
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;

// A few useful battery properties
console.warn("Battery charging: ", battery.charging); // true
console.warn("Battery level: ", battery.level); // 0.58
console.warn("Battery discharging time: ", battery.dischargingTime);

// Add a few event listeners
battery.addEventListener("chargingchange", function(e) {
  console.warn("Battery charge change: ", battery.charging);
}, false);

這些HTML5提供的電池接口API能直接將電池電量狀態告訴web應用,而不需要借助電池傳感器或第三方應用。雖然不是一個特別大的功能,但絕對是一個有用的接口。

閱讀教程
觀看演示

頁面預加載(Link prefetch)API

頁面預加載(Link prefetch)API功能能夠讓瀏覽器在后臺靜悄悄的預先加載/讀取一些頁面或資源到當前頁面,給用戶一個順滑的使用體驗:

<!-- 預加載一個頁面 -->
<link rel="prefetch" href="/misc/goto?guid=4958863952923493466" />

<!-- 預加載一個圖片 -->
<link rel="prefetch"  />

閱讀教程

就是這5個你需要知道和嘗試的新HTML5 API。請注意,這些新功能在幾年之內就會流行起來,所以,越早接受這些API,你就能更好的創造出最前沿技術的Web應用。花幾分鐘試試這些新功能,看看你能用它們實現什么樣的效果!


本文合并了 《你不知道的5個HTML5新功能》和《你不知道的5個HTML5新功能(第二輯)

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!