【问题标题】:Replace script if viewed in IE9?如果在 IE9 中查看替换脚本?
【发布时间】:2011-01-05 15:37:10
【问题描述】:

根据用户浏览器运行不同的 javascript 有多容易?

例如,如果有人使用 IE9 访问该网站,我希望它运行与 Chrome 用户正常运行的脚本不同的脚本。

【问题讨论】:

  • 为什么?可能有更好的方法。

标签: javascript internet-explorer-9


【解决方案1】:

您可以为此使用conditional comments

<!--[if lte IE 6]>
    <script>alert('lte stands for less than or equal to')</script>
<![endif]-->

<!--[if lt IE 7]>
    <script>alert('lt stands for less than')</script>
<![endif]-->

<!--[if gte IE 9]>
    <script>alert('gte stands for greater than or equal to')</script>
<![endif]-->

等等

【讨论】:

    【解决方案2】:

    有多种浏览器检测技术。您可以尝试检测浏览器(通过检查 navigator.userAgent 属性自行检测),或者您可以使用几乎所有 Javascript 框架中可用的方法。例如:

    1. jQuery.browser
    2. Detecting browser with Prototype JS

    您也可以使用conditional comments,但它们只能被 IE 识别。

    -- 帕维尔

    【讨论】:

    • 我确信&lt;!--[if !IE ]&gt; &lt;![endif]--&gt; 在大多数浏览器中都可以使用。不过不要依赖它!这些应该是最后的手段。
    • @Raymos:不,他们没有,这是 IE 特有的功能。 en.wikipedia.org/wiki/Conditional_comment, msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
    • 对。 &lt;!--[if ... IE ]&gt; &lt;![endif]--&gt; 是特定于 IE 的。经过多次尝试和错误,我发现 FF(或 Safari 或 Chrome)并不关心这些代码(这没关系,因为这就是黑客的目的)。所以基本上,您只想使用那些针对 IE(小于、大于、小于或等于等)。所以,&lt;!--[if !IE ]&gt; 有点没用,因为您的目标浏览器(IE 除外)无论如何都不会关心该代码。
    【解决方案3】:

    您可以在 HTML 中使用条件 cmets。

    <!--[if IE]>
       <script src="ie_only.js"></script>
    <![endif]-->
    

    这也可以用于外部样式表

    关于这篇文章的更多信息http://css-tricks.com/how-to-create-an-ie-only-stylesheet/

    【讨论】:

      【解决方案4】:

      我可以推荐特征检测。

      if (someIEAPI) {
          // ie code
      } else if (someChromeAPI) {
          // chrome code
      }
      

      此代码更加健壮,如果 firefox 或 opera 支持其中一种 API,您就不必检查他们的浏览器。

      除了浏览器之外,还有一种习惯是对你撒谎并假装是时髦的东西。

      【讨论】:

        猜你喜欢
        • 2012-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-09
        • 2016-03-18
        • 1970-01-01
        相关资源
        最近更新 更多