判斷 navigator.userAgent 是最直觀的方式,而且適用所有瀏覽器。缺點很明顯:userAgent 字串是給人看的、不是給程式判斷的契約,任何一刻都可能變動,而且很容易偽造。
IE 專有(也就是非標準)的條件註釋是另一條路。它的優點是判斷依據是瀏覽器自己的實作能力,比解析字串可靠:
<!--[if !IE]><!-->
<script type="text/javascript">
alert('非 IE')
</ script>
<!--<![endif]-->
實測這種形式可用。唯一要注意的是 [if IE 8] 中「IE」與「8」之間的空白符是必須的,漏掉就失效。
<!--[if IE 6]>
<input type="hidden" id="ieVersion" value="6" />
<![endif]-->
<!--[if IE 7]>
<input type="hidden" id="ieVersion" value="7" />
<![endif]-->
var ieVersion = (function(){ return document.getElementById('ieVersion')})();
以此類推可以取得各版本資訊,甚至加上 gt、gte 等運算子一次判斷一整類版本。
更實用的變體是把版本寫成 html 標籤的 class:
<!--[if IE 6]>
<html class="ie6">
<![endif]-->
<!--[if IE 7]>
<html class="ie7">
<![endif]-->
<!--[if !IE]><!-->
<html><!--<![endif]-->
這樣 CSS 裡就不需要各種 hack 了,也避免為 IE 額外多載一份樣式表:
xx{} /* 通用 */
.ie6 xx{} /* IE6 專用 */
.ie7 xx{} /* IE7 專用 */
.ie8 xx{} /* IE8 專用 */
既然能寫在頁面裡,當然也能用 JS 動態產生,網路上確實有人這麼做。原理不難,但缺點是把條件註釋綁死在 JS 上——對 CSS 而言就沒用了。
接著還有更「旁門左道」的思路:動態產生一段 HTML,靠瀏覽器實際套用了哪個樣式值來反推版本。最容易想到的形式如下:
<div id="test_1"><span style="color: red; color: #ff6600\0; color: yellow\9\0; *color:green; _color:blue;">測試</span></div>
<script type="text/javascript">
var test_1 = document.getElementById('test_1');
var test_2 = document.createElement('div');
test_2.innerHTML = '<span style="color: red; color: #ff6600\\0; color: yellow\\9\\0; *color:green; _color:blue;">測試</span>';
console.log('test_1:' + test_1.firstChild.style.color + '----' + 'test_2:' + test_2.firstChild.style.color);
</script>
實測結果:
問題就在 IE7:靜態寫在 HTML 裡的與動態 innerHTML 產生的,結果不一致。不確定是 IE7 相容模式的關係還是其他原因。
確認用的最小案例:
<div><span style="*color:red; _color:blue;">原始</span></div>
<script>
var test = document.createElement('div');
test.innerHTML = '<span style="*color:red; _color:blue;">動態生成</span>';
document.body.appendChild(test);
</script>
IE7 的結果:

IE6 的結果:

既然原理與條件註釋類似,而我們只需要比對一次 color 值,簡化後就是:
<div id="test_1"><span style="color: red; color: #ff6600\0; color: yellow\9\0; *color:green; _color:blue;">測試</span></div>
<script type="text/javascript">
var test_1 = document.getElementById('test_1');
var c = test_1.firstChild.style.color;
alert(c=='red'?'other':c=='yellow'?'IE9':c=='#ff6600'?'IE8':c=='green'?'IE7':'IE6');
</script>
實測 IE6 到 IE9 都能正確回報版本。
理論上 Firefox、Chrome/Safari、Opera 也可以用 -moz-、-webkit-、-o- 等私有前綴來判別,但屬性的挑選需要斟酌,像 color 這種通用屬性就不行。
這個偵測手法本質上是「靠 bug 辨識版本」,因此先天脆弱:未來版本或其他瀏覽器是否也有同樣的解析行為並不確定,而且 IE7 那個不一致的現象始終沒查清。
更根本的建議是:別偵測瀏覽器,偵測能力。判斷 'placeholder' in document.createElement('input') 而不是判斷「是不是 IE9」,因為前者問的是「這個功能能不能用」,後者問的是「你是誰」——而真正影響程式碼分支的,永遠是前者。對 CSS 而言,直接用特性查詢 @supports 才是正解。