用JavaScript检测IE浏览器版本 | 您所在的位置:网站首页 › 怎样查询ie版本号信息记录 › 用JavaScript检测IE浏览器版本 |
前端开发中常常会和IE打交道,本文将介绍如何使用javascript来检测IE浏览器的每个版本,包括IE11、IE10、IE9、IE8、IE7、IE6等更旧浏览器,并且还可以叠加,如IE10及以下,IE8及以下,IE6及以下,IE11或者非IE浏览器。文章来自国外文章。 建议一般来说,我们是建议使用条件注释来替换浏览器检测的方法。本文所讲的技术仅仅在条件注释无法实现,或者需要检测一个bug。 IE条件注释: IE10及其以下的浏览器可以通过检测存在非标准的 document.all 对象来区分。 除了上面的特性外,每个IE浏览器还有各自的支持对象 IE版本 支持的标准对象 10+ window.atob 9+ document.addEventListener 8+ document.querySelector 7+ window.XMLHttpRequest 6+ document.compatMode通过上面列出的这些不同IE浏览器版本的检测特性,我们可以组合得到某个特定的IE版本 例如下面的这些组合 IE版本 支持的状态 10及以下 document.all 9及以下 document.all && !window.atob 8及以下 document.all && !document.addEventListener 7及以下 document.all && !document.querySelector 6及以下 document.all && !window.XMLHttpRequest 5.x document.all && !document.compatMode 例子下面的条件代码只会在IE7及一下浏览器中运行 if (document.all && !document.querySelector) { alert('IE7 or lower'); }下面这一个只会运行在IE8中,并且不支持IE7或者IE9: if (document.all && document.querySelector && !document.addEventListener) { alert('IE8'); }下面的条件代码当浏览器为IE11+ 或者非IE时为真 if (!document.all) { alert('IE11+ or not IE'); } 其他方法检测IE版本由于IE11并不再支持条件注释了 检测不同的IE版本对应不同的javascript引擎 IE版本 10 9 8 7 6 JavaScript引擎版本 10 9 5.8 5.7 5.6条件注释 例如下面的代码结合条件注释和JS代码: html代码: var ie = false;在JavaScript文件中: if (7 === ie) { alert('IE7 or lower'); }或者是: var test = document.createElement('div'); test.innerHTML = ''; if ('1' === test.innerHTML) { alert('IE7 or lower'); }相比较使用全局方法,这种方法可能就不优雅并且速度也不是很快。 更进一步还可以进一步将版本号提取成参数,就能生成一个通用的检测IE版本的函数了: var isIE = function(ver){ var b = document.createElement('b') b.innerHTML = '' return b.innerHTML === 1 } if(isIE(6)){ // IE 6 } // ... if(isIE(9)){ // IE 9 }这样想检测哪个版本都毫无压力。但是,如果只想检测是不是IE,而不关心浏览器版本,那只需要在调用函数的时候,不传递参数即可。 var ie = isIE()最后依次贴下在各大浏览器里测试代码的截图。 alert('ie6:' + isIE(6) + '\n' + 'ie7:' + isIE(7) + '\n' + 'ie8:' + isIE(8) + '\n' + 'ie9:' + isIE(9) + '\n' + 'ie:' + isIE()) PS:这样性感的写法让其他又要检测userAgent又要匹配版本号的方法黯然失色。 IE版本代码总结IE11或者非IE if (!document.all) { alert('IE11+ or not IE'); }IE10 if (document.all && document.addEventListener && window.atob) { alert('IE10'); }IE9 if (document.all && document.addEventListener && !window.atob) { alert('IE9'); }IE8上面已经给出 if (document.all && document.querySelector && !document.addEventListener) { alert('IE8'); }IE7 if (document.all && window.XMLHttpRequest && !document.querySelector) { alert('IE7'); }IE6 if (document.all && document.compatMode && !window.XMLHttpRequest) { alert('IE6'); }检测IE版本 var win = window; var doc = win.document; var input = doc.createElement ("input"); var ie = (function (){ //"!win.ActiveXObject" is evaluated to true in IE11 if (win.ActiveXObject === undefined) return null; if (!win.XMLHttpRequest) return 6; if (!doc.querySelector) return 7; if (!doc.addEventListener) return 8; if (!win.atob) return 9; //"!doc.body.dataset" is faster but the body is null when the DOM is not //ready. Anyway, an input tag needs to be created to check if IE is being //emulated if (!input.dataset) return 10; return 11; })(); |
CopyRight 2018-2019 实验室设备网 版权所有 |