4種檢測是否支持HTML5的方法,你知道幾個?

4種檢測是否支持HTML5的方法,你知道幾個?

1,檢查特定的屬性是否存在於全局的對象裏面,比如說window或navigator.
比如geolocation,它是HTML5新加支持的新特性;它是由HTML5工作組以外的Geolocation工作組制定的。要檢查瀏覽器是否支持它可以用一下方法。
function supports_geolocation() {
  return !!navigator.geolocation;
}

2,創建一個元素,檢查特定的屬性是否存在。如檢查是否支持Canvas.
function supports_canvas() {
  return !!document.createElement('canvas').getContext;
}

3,創建一個元素,看特定的方法是否存在於這個元素上。調用這個方法看是否有返回值。比如說檢查video是否支持某種格式。
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,創建一個元素,爲它的屬性設置一個特定的值,看是否這個屬性值被保留。
我們很熟悉Web表單控件,在HTML5裏面又增加了一打這類控件。
<input type="search"> for search boxes
<input type="number"> for spinboxes
<input type="range"> for sliders
<input type="color"> for color pickers
<input type="tel"> for telephone numbers
<input type="url"> for web addresses
<input type="email"> for email addresses
<input type="date"> for calendar date pickers
<input type="month"> for months
<input type="week"> for weeks
<input type="time"> for timestamps
<input type="datetime"> for precise, absolute date+time stamps
<input type="datetime-local"> for local dates and times

爲檢測這些控件是否支持,我們可以用一下方法。
var i = document.createElement("input");
i.setAttribute("type", "color");
return i.type !== "text"; //當瀏覽器不支持這個輸入類型,將返回"text"。

最後介紹一個開源JS類庫:Modernizr(http://www.modernizr.com/),這就是用來封裝檢測HTML5和CSS3功能支持的。一定要使用最新的版本。有了這個類庫,將減少我們很多的代碼。
比如:
1, if (Modernizr.geolocation) //用於檢測是否支持geolocation.
2, if (Modernizr.canvas) //用於檢測是否支持canvas.
3, if (Modernizr.video) { //如果支持video,但需要檢測支持哪種格式呢?
  if (Modernizr.video.webm) {
    // try WebM
  } else if (Modernizr.video.ogg) {
    // try Ogg Theora + Vorbis in an Ogg container
  } else if (Modernizr.video.h264){
    // try H.264 video + AAC audio in an MP4 container
  }
}
4,if (Modernizr.inputtypes.date) //檢測是否支持日期輸入。
 

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