检查是否为ie10

Check for IE 10

本文关键字:ie10 是否 检查      更新时间:2023-09-26

如果用户使用ie10,我如何在页面加载时显示消息框?

function ieMessage() {
    alert("Hello you are using I.E.10");
}

我的网页是一个JSF facet (XHTML)。

在没有条件注释和User Agent嗅探的情况下,真正的检测方法是使用条件编译:

<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
}

参考:当浏览器模式是IE9时,我如何从JS检测IE10 ?


更新:

为了避免注释的最小化,你可以这样使用:

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.isTheBrowserIE.actualVersion(这是从JScript版本的内部值转换而来的)。

一般来说,最好避免User Agent嗅探和条件编译/注释的做法。使用特征检测、优雅退化和渐进增强要好得多。然而,对于少数边缘情况,开发人员可以更方便地检测浏览器版本,您可以使用以下代码片段:

if语句只在ie10上执行

// 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');
}
http://jsfiddle.net/Qz97n/

这里有一个获取当前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!');