how do I run a script only for IE 8

2019-03-22 07:57发布

I have a js file and would like to run some code only if the browser is IE 8. Is there a way I can do this?

Right now I only have this but it's for all ie browsers:

if ($.browser.msie) {
    //do stuff for IE 8
} 

9条回答
你好瞎i
2楼-- · 2019-03-22 08:03

Alright people, I solved it myself like this:

if ($.browser.msie && $.browser.version == 8) {
    //my stuff

} 
查看更多
3楼-- · 2019-03-22 08:08

Browser specific code is almost never a good idea. However, if you must do this, you can put your code inside conditional comments.

http://www.positioniseverything.net/articles/cc-plus.html

<!--[if IE 8]>
  <script type="text/javascript">
    // this is only executed for IE 8
  </script>
<![endif]-->
查看更多
乱世女痞
4楼-- · 2019-03-22 08:08

You can do it with conditional comments (by https://stackoverflow.com/a/10965091/1878731):

<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->

if ($('html').is('.ie8')) {
    ...
}

Or without messing with html (by http://en.wikipedia.org/wiki/Conditional_comment):

<script>
/*@cc_on

  @if (@_jscript_version == 5.8) { // IE8 detected
    // do something
  }
@*/
</script>
查看更多
一纸荒年 Trace。
5楼-- · 2019-03-22 08:12

You can use the document.documentMode to get the version of IE.

switch(document.documentMode)
    {
        case 8:
            //do something with IE8
            break;
        case 9:
            //do something with IE9
            break;
        case 10:
            //do something with IE10
            break;  
        case 11:
            //do something with IE11
            break;
        default:
            console.log('Other browsers...');
    }

For documentation refer here

查看更多
混吃等死
6楼-- · 2019-03-22 08:13

Could you do a call in the header to redirect the page if it is less than IE9? I find myself doing this often for my clients that use a mixture of IE6-10.

In the document head I call,

<!--[if IE 7]>  <link rel="()" type="()" href="(Your link here.)"><![endif]--> 

The other option you could look into is a shim or polyfil. There are many on the internet that help bridge the gap between modern web design and older browsers. An example is Modernizr.

查看更多
贪生不怕死
7楼-- · 2019-03-22 08:18

$.browser is deprecated so you can not use this object property in new jQuery version so to support this you have to use the jQuery migrate plugin.Here is the link. https://github.com/jquery/jquery-migrate/#readme

查看更多
登录 后发表回答