【问题标题】:Check for IE 10 [duplicate]检查 IE 10 [重复]
【发布时间】:2013-04-14 16:30:59
【问题描述】:

如果用户使用的是 IE 10,如何在页面加载时显示消息框?

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

我的网页是 JSF facelet (XHTML)。

【问题讨论】:

  • 为什么需要这样做?
  • 学校项目,必须在不同的浏览器中显示消息:)
  • 只是一个注释——我知道世界告诉我特征检测和优雅降级是要走的路,但是当涉及到使用或避免 ES6(最终是 ES7)特性时,通常的东西只是行不通。我不能在不支持它们的浏览器上使用 'let' 和 'const' 和箭头函数,我想开始使用它们。这让我别无选择,只能检测 IE 10 和 11,并对它们使用不同的脚本。
  • @RyanO'Hara 我在创建自定义滚动条时遇到问题,您在 IE10 中显然无法做到,所以......

标签: javascript internet-explorer internet-explorer-10


【解决方案1】:

一般来说,最好避免用户代理嗅探和条件编译/cmets 的做法。使用 feature detectiongraceful degradationprogressive enhancement 会好得多。不过对于少数几个更方便开发者检测浏览器版本的边缘情况,可以使用如下代码sn-ps:

这个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');
}

http://jsfiddle.net/Qz97n/

【讨论】:

  • 谢谢,现在就试试 :)
  • 非常感谢,工作正常
  • 惊人的代码!我一直在寻找如何做到这一点。 +1 也包括 IE 11 ;)
  • @Alex W,需要做些什么来改进上述解决方案以检测
【解决方案2】:

在没有条件 cmets 和没有用户代理嗅探的情况下检测这一点的真正方法是使用条件编译:

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

参考:How can I detect IE10 from JS when browser mode is IE9?


更新:

为了避免 cmets 的缩小,您可以使用类似:

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 版本的内部值转换而来)。

【讨论】:

  • 然而,在不同的 IE 版本中测试会更烦人。
  • 很好的答案,谢谢。这可以用 IE11 更新吗?
  • 显然没有定义
  • IE11 不支持条件编译。
  • @BenjaminBerger 这个问题专门针对 IE 10,而不是所有版本的 IE。已经确定这不适用于 IE 11(离题),因为它们删除了对条件编译的支持。
【解决方案3】:

下面是获取当前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!');

【讨论】:

  • v 从何而来?
  • @Rhyso 这是您传递给函数的参数 - 在本例中为数字 10。
  • 抱歉应该看一下用法示例:)
猜你喜欢
  • 2013-11-10
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 2019-12-29
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
相关资源
最近更新 更多