如果用户使用的是 IE 10,如何在页面加载时显示消息框?
function ieMessage() {
alert("Hello you are using I.E.10");
}
我的网页是 JSF facelet (XHTML)。
如果用户使用的是 IE 10,如何在页面加载时显示消息框?
function ieMessage() {
alert("Hello you are using I.E.10");
}
我的网页是 JSF facelet (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
}
更新:
为避免缩小评论,您可以使用以下内容:
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!');