如何测试Internet Explorer版本是否为版本7或版本8?

问题描述:

我想测试如果IE是版本7或8,并且它是否阻止特定的代码段运行?如何测试Internet Explorer版本是否为版本7或版本8?

我尝试下面的代码,但这似乎没有工作:

if($.browser.msie && parseInt($.browser.version, 10) <= 8) { 
     $(document).on('mouseenter', '.thumb', function() { 
      $(this).find('.bgg').stop().animate({ opacity : 1 }); 
     }); 

     $(document).on('mouseleave', '.thumb', function() { 
      $(this).find('.bg').stop().animate({ opacity : .5 }); 
     }); 
     } 

理想我真的不想使用这种检测,但在这种情况下,必须使用。

由于只有一个脚本文件的需求,我不得不在我的项目中使用UA嗅探IE。我们不希望@ Kolink的方法需要额外的http请求,也不希望分割功能。对于我会简单地使用:

var ltie9 = $.browser.msie && parseInt($.browser.version, 10) < 9; 

,然后做你想做的使用:

if (ltie9) { ... } 

我有一个jsFiddle显示几种不同的IE检测多达IE10只是为了演示。

+0

全局是丑陋 – Christoph 2012-04-05 12:21:21

+0

我有一个全球唯一的另一件事是,我运行整个脚本我的对象字面命名空间。我不滥用它,因此保持清洁。 – 2012-04-05 12:24:00

+0

为什么不把它包含在你的名字空间呢?全局变量容易发生不必要的修改。 UA嗅探极易出错。 – Christoph 2012-04-05 12:27:27

简单的方法:

<!--[if lte IE 8]><script type="text/javascript"> 
    // specific code for IE8 and below goes here. 
</script><![endif]--> 
+0

+1用于隐藏不必要的其他浏览器。 (尽管以http请求为代价) – Christoph 2012-04-05 12:22:26

使用object detection。 IE7不提供querySelector方法,因此,例如取代

if ($.browser.msie && parseInt($.browser.version, 10) <= 8) 

if (document.all && !document.querySelector) 

Here一些更多的想法

+0

+1引入了doctype嗅探特征检测的一般概念。但是,只有在尝试检测您需要的功能时才能正常工作。使用不相关的功能可能会导致错误。 – Christoph 2012-04-05 12:20:51

+0

任天堂DSi的基于Opera的浏览器也不支持'querySelector'。这是否意味着它是IE7? – 2012-04-05 12:22:03

+0

@Kolink:我没有注意到使用“Nintendo DS”标签的问题OP。 – KooiInc 2012-04-05 12:27:21

IE8可用作和行为像IE7-

来区分,你可以测试document.documentMode

添加属性navigator对象省去了测试再次

//(Run= {}; 

if(window.addEventListener){ 
    Run.handler= function(who, typ, fun){ 
     if(who && who.addEventListener) who.addEventListener(typ, fun, false); 
    }// all browsers except IE8 and below 
} 
else if(window.attachEvent){ 
    /*@cc_on 
    @if(@_jscript_version>5.5){ 
     navigator.IEmod= document.documentMode? 
     document.documentMode:window.XMLHttpRequest? 7:6; 
    } 
    @end 
    @*/ 
    Run.handler= function(who, typ, fun){ 
     if(who && who.attachEvent){ 
      who.detachEvent('on'+typ, fun); 
      who.attachEvent('on'+typ, fun); 
     } 
    } 
}