此篇爲片段翻譯,爲Dive into HTML5系列文章的第三篇,第二篇A Quite Biased History of HTML5 跳過
DETECTING HTML5 FEATURES
DETECTION TECHNIQUES
When your browser renders a web page, it constructs a Document Object Model (DOM), a collection of objects that represent the HTML elements on the page. Every element — every <p>
,
every <div>
, every <span>
—
is represented in theDOM by a different object. (There are also global objects, like window
and document
,
that aren’t tied to specific elements.)
All DOM objects share a set of common properties, but some objects have more than others. In browsers that support HTML5 features, certain objects will have unique properties. A quick peek at the DOM will tell you which features are supported.
There are four basic techniques for detecting whether a browser supports a particular feature. From simplest to most complex:
-
Check if a certain property exists on a global object (such as
window
ornavigator
).Example: testing for geolocation support
-
Create an element, then check if a certain property exists on that element.
Example: testing for canvas support
-
Create an element, check if a certain method exists on that element, then call the method and check the value it returns.
-
Create an element, set a property to a certain value, then check if the property has retained its value.
當你的瀏覽器渲染網頁時,他會構建一個DOM,一個對象的集合,代表頁面上的HTML元素。每個元素——<p>,<div>,<span>在DOM中被表示成爲一個不同的對象。(也有window和document這樣的全局對象,沒有和任何特定的HTML元素相關聯。)
所有的DOM對象都共享一套通用的屬性,不過有些對象有比其他對象更多的屬性。在支持HTML5特性的的瀏覽器裏,特定的對象會擁有獨特的屬性。快速瀏覽一下DOM將會告訴你那些特性是被支持的。
有四種基本技巧可以用來檢測一個瀏覽器是否支持一項特性。從簡到繁分別是:
1.檢測全局對象(比如window和document等)是否存在特定的屬性,如:檢測是否支持地理位置
如果你的瀏覽器支持地理位置的API,在navigator對象中會有geolocation這個屬性。
function supports_geolocation(){
return 'geolocation' in navigator;
}
2.創建一個元素,然後檢測該元素是否存在特定的屬性,如:檢測是否支持canvas
如果你的瀏覽器支持canvas API,那麼創建的代表canvas的DOM對象會有getContext()這個方法。
function supports_canvas() {
return !!document.createElement('canvas').getContext;
}
3.創建一個元素,檢測這個元素是否具備特定方法,然後執行該方法檢查返回值,如:檢測video標籤支持的格式
支持HTML5 video標籤的瀏覽器,創建的video元素會有canPlayType()方法。這個方法會告訴你瀏覽器是否支持某種特定的視頻格式
檢測Mac和iPhone支持的格式
function supports_h264_baseline_video(){
if (!supports_video()) { return false; }
var v = document.createElement("video");
return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}
4.創建一個元素,爲該元素的一個屬性設置一個值,然後檢查這個屬性是否保存了這個值,如,檢測input的type
首先,在創建一個存在內存中的虛擬的<input>元素,input元素的type屬性默認值都是"text",這是極其重要的。
然後,給虛擬的<input>元素設置你所希望檢測的type。
如果你的瀏覽器支持那個獨特的input type,input的type屬性將是你設置的那個值,否則它將忽略你所設置的type值,仍然保留"text"。
var i = document.createElement("input");
i.setAttribute("type","color");
return i.type !== "text";
同時,可以使用Modernizr這樣的js進行檢測