随着html5技术的普及,越来越多的人在使用这项技术做出更炫、效果更好的网页,但是我们使用html5技术的同时,也在为很多浏览器的不支持而感到苦恼,于是我们就可以做两套技术方案,一套提供给浏览器支持html5的用户浏览,一套提供给普通用户浏览。所以就涉及到浏览器是否支持html5,今天我们就来看看有哪些方法来判断浏览器是否支持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功能支持的。一定要使用最新的版本。有了这个类库,将减少我们很多的代码。
比如:
if (Modernizr.geolocation) //用于检测是否支持geolocation.
if (Modernizr.canvas) //用于检测是否支持canvas.
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
}
}
if (Modernizr.inputtypes.date) //检测是否支持日期输入。
5、自定义方法判断浏览器是否支持html5
方法1:
function checkhHtml5() { if (typeof(Worker) !== "undefined") { alert("支持HTML5"); } else { alert("不支持HTML5"); } }
方法2:
if (!document.getElementById("Canvas").getContext) { alert("不支持html5"); } else { alert("支持html5"); }
通过以上内容我们知道了如何判断浏览器是否支持html5?感谢您访问“我爱捣鼓(www.woaidaogu.com)”网站的内容,希望对大家有所帮助!引用本文内容时,请注明出处!谢谢合作!