如果用户使用IE 10,我该如何使消息框在页面加载时出现?
function ieMessage() {
alert("Hello you are using I.E.10");
}
我的网页是一个JSF面板(XHTML)。
如果用户使用IE 10,我该如何使消息框在页面加载时出现?
function ieMessage() {
alert("Hello you are using I.E.10");
}
我的网页是一个JSF面板(XHTML)。
检测这个问题的真正方法,不需要使用条件注释和用户代理嗅探,而是使用条件编译:
<script type="text/javascript">
var isIE10 = false;
/*@cc_on
if (/^10/.test(@_jscript_version)) {
isIE10 = true;
}
@*/
console.log(isIE10);
</script>
运行此代码后,您随时可以使用以下内容:if (isIE10) {
// Using Internet Explorer 10
}
参考资料:如何检测IE10在IE9浏览器模式下?
更新:
为了避免注释被压缩,你可以使用类似以下的方法:
var IE = (function () {
"use strict";
var ret, isTheBrowser,
actualVersion,
jscriptMap, jscriptVersion;
isTheBrowser = false;
jscriptMap = {
"5.5": "5.5",
"5.6": "6",
"5.7": "7",
"5.8": "8",
"9": "9",
"10": "10"
};
jscriptVersion = new Function("/*@cc_on return @_jscript_version; @*/")();
if (jscriptVersion !== undefined) {
isTheBrowser = true;
actualVersion = jscriptMap[jscriptVersion];
}
ret = {
isTheBrowser: isTheBrowser,
actualVersion: actualVersion
};
return ret;
}());
你可以像这样访问属性:IE.isTheBrowser
和IE.actualVersion
(这是从JScript版本的内部值转换而来)。
一般来说,最好避免使用用户代理嗅探和条件编译/注释。相比之下,更好的方法是使用特性检测、优雅降级和渐进增强。然而,在极少数需要检测浏览器版本的情况下,可以使用以下代码片段:
此 if
语句仅在 IE 10 上执行。
// IF THE BROWSER IS INTERNET EXPLORER 10
if (navigator.appVersion.indexOf("MSIE 10") !== -1)
{
window.alert('This is IE 10');
}
这个if
语句只会在IE 11上执行
// IF THE BROWSER IS INTERNET EXPLORER 11
var UAString = navigator.userAgent;
if (UAString.indexOf("Trident") !== -1 && UAString.indexOf("rv:11") !== -1)
{
window.alert('This is IE 11');
}
以下是获取当前IE浏览器或IE版本的方法:
function IE(v) {
return RegExp('msie' + (!isNaN(v)?('\\s'+v):''), 'i').test(navigator.userAgent);
}
以下是您如何使用它的方法:
if(IE()) alert('Internet Explorer!');
if(IE(10)) alert('Internet Explorer 10!');