DiveIntoHTML5翻译(2)——检测HTML5特性

此篇为片段翻译,为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.)

girl peeking out the window

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:

  1. Check if a certain property exists on a global object (such as window ornavigator).

    Example: testing for geolocation support

  2. Create an element, then check if a certain property exists on that element.

    Example: testing for canvas support

  3. Create an element, check if a certain method exists on that element, then call the method and check the value it returns.

    Example: testing which video formats are supported

  4. Create an element, set a property to a certain value, then check if the property has retained its value.

    Example: testing which <input> types are supported

检测技巧


当你的浏览器渲染网页时,他会构建一个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进行检测




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章