HTML5提供了一些很是强大的JavaScript和HTML API,来帮助开发者构建精彩的桌面和移动应用程序。本文将介绍5个新型的API,但愿对你的开发工做有所帮助。
1. 全屏API(Fullscreen API)
该API容许开发者以编程方式将Web应用程序全屏运行,使Web应用程序更像本地应用程序。
php
- function launchFullScreen(element) {
- if(element.requestFullScreen) {
- element.requestFullScreen();
- } else if(element.mozRequestFullScreen) {
- element.mozRequestFullScreen();
- } else if(element.webkitRequestFullScreen) {
- element.webkitRequestFullScreen();
- }
- }
-
- launchFullScreen(document.documentElement);
- launchFullScreen(document.getElementById("videoElement"));
教程 / 演示
2. 页面可见性API(Page Visibility API)
该API能够用来检测页面对于用户的可见性,即返回用户当前浏览的页面或标签的状态变化。
css
- 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";
- }
-
- document.addEventListener(visibilityChange, function(e) {
-
- }, false);
教程 / 演示
3. getUserMedia API
该API容许Web应用程序访问摄像头和麦克风,而无需使用插件。
html
- window.addEventListener("DOMContentLoaded", function() {
-
- 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);
- };
-
-
- if(navigator.getUserMedia) {
- navigator.getUserMedia(videoObj, function(stream) {
- video.src = stream;
- video.play();
- }, errBack);
- } else if(navigator.webkitGetUserMedia) {
- navigator.webkitGetUserMedia(videoObj, function(stream){
- video.src = window.webkitURL.createObjectURL(stream);
- video.play();
- }, errBack);
- }
- }, false);
教程 / 演示
4. 电池API(Battery API)
这是一个针对移动设备应用程序的API,主要用于检测设备电池信息。
html5
- var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
-
- console.warn("Battery charging: ", battery.charging);
- console.warn("Battery level: ", battery.level);
- console.warn("Battery discharging time: ", battery.dischargingTime);
-
- battery.addEventListener("chargingchange", function(e) {
- console.warn("Battery charge change: ", battery.charging);
- }, false);
教程
5. Link Prefetching
预加载网页内容,为浏览者提供一个平滑的浏览体验。
web
- <link rel="prefetch" href="http://davidwalsh.name/css-enhancements-user-experience" />
-
- <link rel="prefetch" href="http://davidwalsh.name/wp-content/themes/walshbook3/images/sprite.png" />
教程
编程