怎么对HTML 5的特性做检测?

Center

随着HTML 5的流行,现在HTML 5占据了主要的市场份额,HTML 5增加了很多的新功能,这些新功能可以让Web体验变得更好。大多数特性在现代的主流浏览器中获得了支持,因此我们可以放心使用这些新特性来增加Web体验。但是,当有新版本的浏览器发布时,我们不要忘记一些旧版本或者老的浏览器。

目前的另外一个事实是,用户想用旧版本的浏览器来支持新特性。因此建立的产品必须是跨浏览器的,而我们唯一能做的就是HTML5特性检测,来确保指定特性被浏览器支持时才执行代码。

Modernizr是一个非常好的JS库,它可以完成对HTML 5和CSS 3的特性检测。默认情况下,modernizr会对所有特性进行检测(当然可以自定义),但如果你只想检测某一个特定功能而不像引入整个JS库,那你就得把代码放在正确的位置。在这篇文章中,我们将会看到如何使用原生的js和modernizr来检测HTML 5 的特性。

Canvas

// JS
return !!document.createElement('canvas').getContext;

// Modernizr
if (Modernizr.canvas) {

}

Video

// JS
return !!document.createElement('video').canPlayType;

// Modernizr
if (Modernizr.video) {

}

Local Storage

// JS
return 'localStorage' in window && window['localStorage'] !== null;

// Modernizr
if (Modernizr.localstorage) {

}

Web Workers

// JS
return !!window.Worker;

// Modernizr
if (Modernizr.webworkers) {

}

Offline Web Application

// JS
return !!window.applicationCache;

// Modernizr
if (Modernizr.applicationcache) {

}

Geolocation

// JS
return 'geolocation' in navigator;

// Modernizr
if (Modernizr.geolocation) {

}

Placeholder Text

// JS
var i = document.createElement('input');
return 'placeholder' in i;

// Modernizr
if (Modernizr.input.placeholder) {

}

Form Autofocus

// JS
var i = document.createElement('input');
return 'autofocus' in i;

// Modernizr
if (Modernizr.input.autofocus) {

}

Microdata

// JS
return !!document.getItems;

// Modernizr does not provide support to detect Microdata

History API

(关于其介绍,请戳:http://www.ido321.com/1069.html)

// JS
return !!(window.history && history.pushState);

// Modernizr
if (Modernizr.history) {

}

到目前为止,这是我收集的特性检测的代码列表。如果你有特性检测的代码想要在列表中分享,也可以告诉我。

原文首发:http://www.ido321.com/1116.html

原文地址:https://www.cnblogs.com/10manongit/p/12676213.html