代码之家  ›  专栏  ›  技术社区  ›  Parand

使用Javascript/jQuery检测IE6

  •  3
  • Parand  · 技术社区  · 15 年前

    我需要检测IE6以解决缺乏position:fixed. 我一直在使用一个简单的正则表达式:

    var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
    

    这几乎一直有效,除了浏览器声称同时是IE6和IE7的用户:

    Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1; .NET CLR 3.0.04506.30)
    

    很光荣。

    我很想用 jquery.support ,但它似乎不支持查询position:fixed is 可用。所以我又开始检测IE6了。

    有各种建议的解决方案,例如 looking for the existence of maxHeight

    我正在考虑使用有条件的评论-这样至少它将是IE本身声称是IE6,而不是黑客。比如:

    <!--[if IE 6]>
    <SCRIPT> var isIE6 = true; </SCRIPT>
    <![endif]-->
    

    或者有一个f unction that directly tests if position:fixed is available ,但这似乎有点沉重。

    有什么理由我的条件评论方法不起作用吗?有更好的方法吗?

    6 回复  |  直到 10 年前
        1
  •  5
  •   Nick Craver    15 年前

    Paul Irish 写的 an addition $.support 专门用于检查 position: fixed 支持。我建议你走这条路,尽可能使用特征检测而不是浏览器检测。

    除此之外,您只需要包含最后一个函数,这部分:

    $.support.positionFixed = (function() { ..... })();
    

    在jQuery之后包含它,然后可以在代码中使用它,如下所示:

    if(!$.support.positionFixed) {
      //handle browsers that don't support it
    }
    
        2
  •  6
  •   Seth    15 年前
    <script type="text/javascript">
        if (nothing_works) {
            is_ie6 = true;
        }
    </script>
    

    不过,说真的,你的条件评论可能是最好、最准确的检测方法。即使浏览器位于用户代理中,它也不会像解析IE6那样解析条件注释。

    我得回家哭一小会儿,因为我知道有人还在为IE6开发。

        3
  •  1
  •   Hristo    15 年前

    我遇到的克服IE问题的最佳方法是使用条件注释:

    <!--[if IE 6]>
    ... link IE 6 specific stylesheet or a script...
    <![endif]-->
    

    这种方法还将使您的页面向前兼容,以便IE的未来版本可以在不需要所有IE6(及更低版本)样式的情况下呈现它。

        4
  •  0
  •   Ian Wetherbee    15 年前

    http://api.jquery.com/jQuery.browser/

    if ($.browser.msie && parseInt($.browser.version) == 6) {
      // do something
    }
    
        5
  •  0
  •   sukru    15 年前

    IE博客上有一篇关于功能检测的详细文章:

    http://blogs.msdn.com/b/ie/archive/2010/04/14/same-markup-writing-cross-browser-code.aspx

    基本上,他们(可以理解)反对浏览器版本检测:

    “不要:检测特定浏览器”

    有太多的场景(如您的示例中)使得浏览器对其版本撒谎,最好使用特性检测。

        6
  •  0
  •   Gabriel    15 年前

    <!--[if IE 6]>
    <script type="text/javascript" src="ie6.js"></script>
    <![endif]-->