如何检测浏览器是否支持HTML 5
HTML 5是最新的HTML标准,包括许多新的变化和功能。可以通过三种方法检测HTML 5的支持:
方法1:检查地理位置支持
浏览器的HTML5中添加了地理位置API。它用于识别用户的位置。可以通过检查navigator对象中是否存在 geolocation 属性来检测此API的存在。这可以通过使用navigator.geolocation来实现,它返回地理位置对象。如果该对象存在,则说明浏览器支持HTML5。
示例:
How to detect HTML 5 is supported
or not in the browser ?
GeeksforGeeks
How to detect HTML5 support
in the browser ?
Geolocation features is added in HTML5.
Checking the Geolocation supports.
Click on the button to check
for Geolocation support
Gelocation is supported:
Check for Geolocation
function checkGeolocation() {
if (navigator.geolocation)
isSupported = true;
else
isSupported = false;
document.querySelector('.output').textContent
= isSupported;
}
输出:
点击按钮之前:
点击按钮后:
方法2:检查Canvas元素
Canvas元素用于渲染形状或位图元素。这是HTML5新增的功能。
Canvas元素有一个 getContext() 方法,用于返回Canvas元素的绘图上下文。如果不支持此上下文标识符,则返回null值。可以使用此属性来检查是否支持Canvas元素。
使用document.createElement()方法创建一个新的Canvas元素。通过访问创建的输入对象上的getContext方法来检查,然后使用if语句检查此表达式的结果。如果结果为true,表示浏览器支持HTML5。
示例:
How to detect HTML 5 is supported
or not in the browser ?
GeeksforGeeks
How to detect that HTML5 is
not supported by JavaScript?
The Canvas features added in HTML5. Checking
for canvas support in HTML5.
Click on the button to check
for Canvas support
Canvas is supported:
Check for canvas
function checkCanvas() {
if (document.createElement('canvas').getContext)
isSupported = true;
else
isSupported = false;
document.querySelector('.output').textContent
= isSupported;
}
输出:
在点击按钮之前:
点击按钮后:
方法3:检查文本输入类型
HTML5引入了新的输入类型,可以用于输入不同形式的数据,并进行验证。HTML5之前的输入元素不支持这些新类型,使用它们会自动恢复到默认的“文本”类型。这可以用来检查浏览器是否支持HTML5。
使用document.createElement()方法创建一个新的输入元素。然后,在创建的元素上使用setAttribute方法设置输入类型为任何新的输入类型之一。使用if语句检查此元素的类型,看它是否与默认的“文本”值匹配。如果值没有恢复到默认设置,说明浏览器支持HTML5。
示例:
How to detect HTML 5 is supported
or not in the browser ?
GeeksforGeeks
How to detect HTML5 support
in the browser ?
New input types are one of the
features added in HTML5.
Checking for the new input types
means that HTML5 is supported.
Click on the button to check if
the new input types are supported
New input types supported:
Check for input types
function checkInputType() {
let tempElement = document.createElement("input");
tempElement.setAttribute("type", "color");
// Check if the type attribute falls back
// to default text type
if (tempElement.type !== "text")
isSupported = true;
else
isSupported = false;
document.querySelector('.output').textContent
= isSupported;
}
输出:
点击按钮前:
点击按钮后: