繁体   English   中英

我如何只为IE 8运行脚本

[英]how do I run a script only for IE 8

我有一个js文件,并且仅在浏览器为IE 8时才想运行一些代码。有什么办法可以做到这一点?

现在我只有这个,但是它适用于所有浏览器:

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

看到JavaScript中的浏览器检测? http://modernizr.com

这是最简短的答案:

if (navigator.userAgent.match(/MSIE 8/) !== null) {
  // do something in IE8
}

浏览器特定的代码几乎从来都不是一个好主意。 但是,如果必须执行此操作,则可以将代码放入条件注释中。

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

<!--[if IE 8]>
  <script type="text/javascript">
    // this is only executed for IE 8
  </script>
<![endif]-->

好的,我自己这样解决了它:

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

} 

如果页面小于IE9,您可以在标题中进行调用以重定向页面吗? 我发现自己经常为使用IE6-10的客户这样做。

在文件头中,我称

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

您可能要考虑的另一个选项是垫片或polyfil。 互联网上有许多内容可以帮助缩小现代网页设计和旧版浏览器之间的差距。 一个示例是Modernizr

您可以使用条件注释来做到这一点(通过https://stackoverflow.com/a/10965091/1878731 ):

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

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

或不弄乱html(通过http://en.wikipedia.org/wiki/Conditional_comment ):

<script>
/*@cc_on

  @if (@_jscript_version == 5.8) { // IE8 detected
    // do something
  }
@*/
</script>

您可以执行以下操作:

if (navigator.userAgent.indexOf('MSIE 8.0') !== -1) {
  // this clause will only execute on IE8
}

$ .browser已过时,因此您不能在新的jQuery版本中使用此对象属性,因此要支持此功能,您必须使用jQuery migration插件。以下是链接。 https://github.com/jquery/jquery-migrate/#readme

您可以使用document.documentMode获取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...');
    }

有关文档,请参见此处

尝试像这样使用

<script type="text/javascript">
    if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
        document.write('<script src="somescript.js"><\/script>');
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM