2011-04
06
10:18
Doomin

一段巧妙的判断IE浏览器版本的js代码

分类:前端开发标签:

下面这段代码使用IE可以识别html注释的特性,可以准确的判断IE浏览器的版本号,没有使用诸多怪异的测力检测方法,超级简洁。
原作者的代码地址在这里,我做了一点小改动,文中有注释,可以到这里运行测试。

Javascript Code
/**
 * ie equals one of false|6|7|8|9 values, ie5 is fucked down.
 * Based on the method: https://gist.github.com/527683
 */
var ie = function () {
    var v = 4, //原作者的此处代码是3,考虑了IE5的情况,我改为4。
        div = document.createElement('div'),
        i = div.getElementsByTagName('i');
    do {
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->';
    } while (i[0]);
    return v > 5 ? v : false; //如果不是IE,之前返回undefined,现改为返回false。
}();

共有2条评论

  1. 坚强的小展 2011-04-25 10:11

    强大,果然很简洁,以后就用这个了

  2. 踏雪 2011-08-25 15:18

    还有:
    只有一行代码,只针对IE起作用,而且考虑了IE用户自选渲染模式、怪癖模式、支持IE5、6、7、8、9及10。

    /*@cc_on alert(document.documentMode||( document.compatMode == "CSS1Compat" ? "XMLHttpRequest" in window ? @_jscript_version*10-50 : 6 : 5)) @*/

    // 说明:必须包含/*@cc_on …. @*/,因为这是IE的编译模式

发表评论

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>