2014-02-12 18 views
0

我想檢測瀏覽器&然後我需要根據瀏覽器加載css文件。爲此我使用以下javascript.But問題是我使用它的任何瀏覽器顯示Mozilla作爲代碼名稱。使用appCodeName檢測瀏覽器並加載一些css

<script type="text/javascript"> 
browsername=navigator.appCodeName; 
alert(browsername); //<- always alert Mozilla if i run in IE or Safari 
</script> 

第二件事是如果瀏覽器是IE瀏覽器,那麼我需要加載一些CSS。

回答

0

可以使用條件註釋加載CSS文件:

<p class="accent"> 
<!--[if IE]> 
According to the conditional comment this is IE<br /> 
<![endif]--> 
<!--[if IE 6]> 
According to the conditional comment this is IE 6<br /> 
<![endif]--> 
<!--[if IE 7]> 
According to the conditional comment this is IE 7<br /> 
<![endif]--> 
<!--[if IE 8]> 
According to the conditional comment this is IE 8<br /> 
<![endif]--> 
<!--[if IE 9]> 
According to the conditional comment this is IE 9<br /> 
<![endif]--> 
<!--[if gte IE 8]> 
According to the conditional comment this is IE 8 or higher<br /> 
<![endif]--> 
<!--[if lt IE 9]> 
According to the conditional comment this is IE lower than 9<br /> 
<![endif]--> 
<!--[if lte IE 7]> 
According to the conditional comment this is IE lower or equal to 7<br /> 
<![endif]--> 
<!--[if gt IE 6]> 
According to the conditional comment this is IE greater than 6<br /> 
<![endif]--> 
<!--[if !IE]> --> 
According to the conditional comment this is not IE 5-9<br /> 
<!-- <![endif]--> 
</p> 

而且這裏的一些代碼,使用JavaScript來檢測瀏覽器:

navigator.sayswho = (function() { 
    var N = navigator.appName, 
     ua = navigator.userAgent, 
     tem; 
    var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i); 
    if (M && (tem = ua.match(/version\/([\.\d]+)/i)) != null) M[2] = tem[1]; 
    M = M ? [M[1], M[2]] : [N, navigator.appVersion, '-?']; 

    return M; 
})(); 

例子:http://jsfiddle.net/32cj6/

+0

IE10(或者11)停止關注條件註釋。 –

0

也有HTML檢查IE的標籤:

<!--[if IE]> 
     <link rel="stylesheet" type="text/css" href="internet_explorer_styling.css" /> 
    <![endif]--> 

當然你也可以使用JavaScript。使用下面的代碼:

navigator.userAgent 

navigator.appVersion 

如果使用JavaScript這一點,那麼你應該檢查這些字符串的1含有鉻,火狐,歌劇或IE(IE = MSIE)

希望這會幫助你!

祝你好運!

0

「有些瀏覽器誤認自己旁路現場測試」:http://www.w3schools.com/js/js_window_navigator.asp

嘗試採取一看,這也:
Browser detection in JavaScript?

要讓IE特定的CSS,那麼你可以做這樣的事情在頭與內聯的CSS或鏈接的樣式表:

<!--[if IE]> 
    <style type="text/css"> 
    .selector { 
     color: #000; 
    } 
    </style> 
    <link rel="stylesheet" href="IEstyle.css"> 
<![endif]--> 

還可以做具體的版本的IE,例如[如果LTE IE9]將是如果小於或等於IE9。 [如果IE9]會大於IE9,依此類推。

0

我用document.documentMode!= undefined document.documentMode檢查IE是否運行IE。 但你也可以尋找(的ScriptEngine()==「的JScript」) 有IE的多很多,例如枚舉在JScripts定義,它可以讓經過數據文件系統 的ActiveXObject是在JScript

定義signifancts

如果(typeof運算枚舉== 「功能」 & &的typeof的ActiveXObject == 「功能」)你有IE和因此n