检测浏览器是否支持HTML5功能
在用HTML5开发Web App时,检测浏览器是否支持HTML5功能是个必须的步骤。
检测浏览器是否支持HTML5功能,可归结为以下四种方式:
- 在全局对象上检测属性;
- 在创建的元素上检测属性;
- 检测一个方法是否返回期望值;
- 检测元素是否能保留值。
1. 在全局对象上检测属性
比如,检测离线功能的代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!doctype html><html lang="cn"><head> <meta charset="UTF-8"> <title>applicationCache Test</title> <script> window.onload = function() { if (window.applicationCache) { document.write("Yes, your browser can use offline web applications."); } else { document.write("No, your browser cannot use offline web applications."); } } </script></head><body></body></html> |
2. 在创建的元素上检测属性
首先要创建一个元素,再检测其能否为DOM识别。比如,通过测试canvas元素的context属性,检测浏览器是否支持canvas元素:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!doctype html><html lang="cn"><head> <meta charset="UTF-8"> <title>Simple Square</title> <script type="text/javascript"> window.onload = drawSquare; function drawSquare () { var canvas = document.getElementById('Simple.Square'); if (canvas.getContext) { var context = canvas.getContext('2d'); context.fillStyle = "rgb(13, 118, 208)"; context.fillRect(2, 2, 98, 98); } else { alert("Canvas API requires an HTML5 compliant browser."); } } </script></head><body> <canvas id="Simple.Square" width="100" height="100"></canvas></body></html> |
3. 检测一个方法是否返回期望值
我们知道,浏览器对WebM、H.264的支持是不尽相同的。如何检测浏览器支持哪种编解码器?首先要像前面“2. 在创建的元素上检测属性”所述那样,先检测是否支持该元素(比如video),再检测方法是否返回期望值:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<!doctype html><html lang="cn"><head> <meta charset="UTF-8"> <title>Video Test</title> <script> function videoCheck() { return !!document.createElement("video").canPlayType; } function h264Check() { if (!videoCheck) { document.write("not"); return; } var video = document.createElement("video"); if (!video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) { document.write("not"); } return; } document.write("Your browser does "); h264Check(); document.write(" support H.264 video."); </script></head><body></body></html> |
4. 检测元素是否能保留值
HTML5表单元素的检测只能用这种方法,比如input的range类型,如果浏览器不支持,则会显示一个普通的文本框,具体检测方法如下所示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<!doctype html><html lang="cn"><head> <meta charset="UTF-8"> <title>Range Input Test</title> <script> function rangeCheck() { var i = document.createElement("input"); i.setAttribute("type", "range"); if (i.type == "text") { document.write("not"); } return; } document.write("Your browser does "); rangeCheck(); document.write(" support the <code><input type=range></code> input type."); </script></head><body></body></html> |
posted on
浙公网安备 33010602011771号