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) //检测是否支持日期输入。

原文地址:https://www.cnblogs.com/kt520/p/3644038.html