簡體   English   中英

如何使用條件編譯來嗅探 IE8

[英]How to use conditional compile to sniff IE8

我想嗅探當前版本的 IE8(我很抱歉,但別無他法,我必須這樣做)。 我知道應該使用特征嗅探而不是瀏覽器嗅探,但是,嘿,我的老板不知道,對吧?

現在我使用了這個條件編譯代碼:

var ie8 = false/*@cc_on @_jscript_version == 8@*/

但似乎它也包括IE7。 任何想法?

在不使用條件編譯的情況下,您可以使用條件注釋在html元素上為要測試的每個 IE 設置 class,例如:

<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->

(來自http://initializr.com/

那么在JS中測試class就很簡單了:

var ie8 = !!document.getElementsByTagName("html")[0].className.match(/ie8/);

以下假設您使用的是 Internet Explorer...

首先,測試瀏覽器版本是非常不正常的——應該測試document.documentMode(因為一個頁面即使使用IE9或IE10也可以是IE8模式):

if (document.documentMode == 8) { ...

如果您有一些非常奇怪的要求,那么您可以可靠地檢測 JScript 版本,例如 _jscript_version 是 IE8 的 5.8(請參閱http://en.wikipedia.org/wiki/Conditional_comment ):

var ieJsVer = Function('return/*@cc_on @_jscript_version @*/;')();
var isIE8 = (ieJsVer == 5.8);

條件注釋被放在一個字符串中,這樣它就不會被任何可能發生的 JavaScript 壓縮刪除(這可能會刪除注釋)。

重要的Internet Explorer 11編輯:

  • 添加; 在 Function() 字符串的末尾 - 否則 EDGE 模式下的 IE11 會引發異常 - 啊!
  • IE11 處於 EDGE 模式,然后 ieJsVer 未定義
  • docMode 中的 IE11 <= 10 然后 ieJsVer 為 11
  • EDGE 模式下的 IE11 為 document.documentMode 返回 undefined

為什么不使用條件注釋來切換設置變量的腳本? 喜歡:

<head>
    <script>
        window.ie8 = false;
    </script>
    <!--[if IE 8]>
        <script>
            window.ie8 = true;
        </script>
    <![endif]-->
</head>

當然它有點冗長,但也許它也更可靠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM