下面来看看源代码先(我会在后面解读大牛思想和代码中的难点讲解) 复制代码 代码如下: // ---------------------------------------------------------- // A short snippet for detecting versions of IE in JavaScript // without resorting to user-agent sniffing // ---------------------------------------------------------- // If you"re not in IE (or IE version is less than 5) then: // ie === undefined // If you"re in IE (>=5) then you can determine which version: // ie === 7; // IE7 // Thus, to detect IE: // if (ie) {} // And to detect the version: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // ie < 9 // Anything less than IE9 // ---------------------------------------------------------- // UPDATE: Now using Live NodeList idea from @jdalton var ie = (function(){ var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i"); while ( div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->", all[0] ); return v > 4 ? v : undef; }());
一个很精辟的代码,但可以完美检测出ie的各个版,还可以一次按范围检测,在源码的注释中教练你怎么使用。 原理: 动态创建一个div,利用ie条件注释来往里面插入一个i标签,在来检测i标签是否添加来判断是否是ie浏览器。在while中不断循环来比对ie的版本。 下面我们来理解这段代码: 复制代码 代码如下: var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i"); //这段好理解,声明变量和创建一个div,获取div中的i div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->", //这个就是核心,利用的ie条件注释来完成,ie的条件注释是向后兼容的,所以可以用这检测以后出的ie10,如果下一个版本叫ie10的话。