Javascript 如何使用javascript或jquery检测IE7并将类添加到div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3670138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:39:15  来源:igfitidea点击:

How to detect IE7 with javascript or jquery and add a class to div

javascriptjqueryinternet-explorer-7

提问by shin

Is there any way to detect IE7?

有没有办法检测IE7?

I don't have any problems with my codes in IE8, but I have a problem with IE7.

我在 IE8 中的代码没有任何问题,但是我在 IE7 中遇到了问题。

So what I thought is that I can add a class with jquery when a browser is IE7 detecting it by javascript.

所以我想的是,当浏览器是 IE7 通过 javascript 检测它时,我可以添加一个带有 jquery 的类。

I want to change from

我想从

<div id="system">

to

<div id="system" class="ie7">

Thanks in advance.

提前致谢。

采纳答案by Jimmy

You could use an IE conditional comment to add the class via javascript, something like this:

您可以使用 IE 条件注释通过 javascript 添加类,如下所示:

<!--[if IE 7]>
<script type="text/javascript">
$(document).ready(function() {
    $('#system').addClass('ie7');
});
</script>
<![endif]-->

回答by Alex

if you really want to solve this by using javascript you might want to check the version like this:

如果你真的想通过使用 javascript 来解决这个问题,你可能需要像这样检查版本:

if (navigator.appVersion.indexOf("MSIE 7.") != -1)
    $('#system').addClass('ie7');

回答by jAndy

You can do it just with HTML:

你可以只用 HTML 来做:

css

css

.ie7{
   padding: 0;
   color: red;
}

html

html

<!--[if IE 7 ]> <div id="system" class="ie7"> <![endif]-->
<!--[if (gt IE 7)|!(IE)]><!--> <div id="system"> <!--<![endif]-->
</div>

This creates the divwith the class ie7if executed in internet explorer 7. All other browser and IE > 7 would just create that div without the class.

如果在 Internet Explorer 7 中执行,这将创建divie7。所有其他浏览器和 IE > 7 将只创建没有类的 div。

回答by Todd Moses

To detect ie7 just use

要检测 ie7 只需使用

if($.browser.msie && parseFloat($.browser.version) < 8){
    //do other stuff
    return;
}

To do what you want with it just:

用它做你想做的事:

if($.browser.msie && parseFloat($.browser.version) < 8){
    $('#system').addClass('ie7');
}

回答by Enlightened

Try this:

尝试这个:

<!--[if IE 7]>
<script type="text/javascript">
  $('#system').addClass('ie7');
</script>
<![endif]-->

回答by Vignesh Subramanian

Please be informed that IE8 compat view will also have <!--[if IE 7 ]>as true

请注意,IE8 兼容视图也将具有<!--[if IE 7 ]>相同的功能

So you should do a second level test on the document mode, if you dont want the changes to be reflecting in IE8 Compat view.

因此,如果您不希望更改反映在 IE8 Compat 视图中,您应该对文档模式进行二级测试。

<!--[if IE 7]>
    <script type="text/javascript"> 
   try
    {
    if(document.documentMode!=8){
     //Your code comes here
    }
    }
    catch(exception){
    }
   </script>
<!--<![endif]-->