檢測瀏覽器是否支持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
>
|