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

对着背影说爱祢 提交于 2020-01-01 04:22:13

问题


Is there any way to detect IE7?

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

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

I want to change from

<div id="system">

to

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

Thanks in advance.


回答1:


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

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



回答2:


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

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



回答3:


You can do it just with HTML:

css

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

html

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

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




回答4:


To detect ie7 just use

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');
}



回答5:


Try this:

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



回答6:


Here's a few different ways:

  • http://gmatter.wordpress.com/2006/11/21/another-way-to-detect-ie7-in-javascript/
  • http://api.jquery.com/jQuery.browser/#jQuery.browser.version2
  • http://ajaxian.com/archives/detecting-ie7-in-javascript



回答7:


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

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.

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


来源:https://stackoverflow.com/questions/3670138/how-to-detect-ie7-with-javascript-or-jquery-and-add-a-class-to-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!