如果浏览器版本低于IE9,则执行特定的JavaScript。

6
如果浏览器低于IE9,我希望在jQuery中执行特定的代码。是的,我已经知道了。
<!--[if ... IE ]> <![endif]-->

但我想要的是在脚本标签内使用jQuery document.ready来检查此条件。
<script>
    $(document).ready(function(){
        //code to check if lt ie9 
    });
</script>

你是否考虑过使用特性检测而不是浏览器检测? - Spudley
2个回答

14

您可以通过在<html>元素上使用类来针对旧版Internet Explorer(<=9)进行目标定位...

<!--[if lt IE 7]>  <html class="ie ie6 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 7]>     <html class="ie ie7 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 8]>     <html class="ie ie8 lte9 lte8"> <![endif]-->
<!--[if IE 9]>     <html class="ie ie9 lte9"> <![endif]-->
<!--[if gt IE 9]>  <html> <![endif]-->
<!--[if !IE]><!--> <html>             <!--<![endif]-->

...然后检查<html>是否有类.lt9.lt8 - 无论你所针对的是哪个版本的Internet Explorer:

if($('html').hasClass('lte9')) { /* LTE IE9 */ }

不过,我建议使用Modernizr特性检测而不是检查特定的浏览器。


这是最可靠和未来性的方法,适用于在JavaScript和CSS中分叉IE,并被所有其他浏览器视为HTML注释。 - André Dion

2

2
亲爱的_Aegis_,请避免仅提供链接的答案,因为当链接过时时,有价值的信息将会丢失。相反,这里请给出您核心思想的附加描述。谢谢! - Trinimon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接