有些效果在舊版 IE 中的呈現方式實在太糟,只能針對特定版本餵一份不同的 CSS。這個需求拆開來其實只有兩個關鍵點:一是判斷瀏覽器版本,二是動態修改樣式表的路徑。
第二點的用途遠不只 hack——即時切換網站模板、論壇風格切換,本質上都是同一件事:換掉 link 的 href。
<script type="text/javascript">
var browser = navigator.appName
var b_version = navigator.appVersion
var version = b_version.split(";");
try {
// 代碼只針對 ie 浏覽器有效,為了避免在其他浏覽器報錯,
// 可以用 try{代碼體}catch(err){代碼體} 來消除報錯
var trim_Version = version[1].replace(/[ ]/g, "");
if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE7.0") {
// 將 "your-stylesheet-url" 替換成想在 ie7 中加載的樣式表的路徑
document.styleSheets[0].href = "your-stylesheet-url";
}
else if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE6.0") {
document.styleSheets[0].href = "your-another-stylesheet-url";
}
}
catch (err) { //捕捉錯誤後不作任何處理也可
}
</script>
核心就一句:document.styleSheets[0].href。指定第幾份樣式表的 href,瀏覽器就會去重新載入對應的 CSS 檔案。用 try/catch 包住是因為 navigator.appVersion 的格式在各瀏覽器上不一致,直接取 version[1] 在非 IE 環境下可能得到 undefined 而拋錯。
與其依賴 appName 加 appVersion 的字串比對,直接解析 userAgent 反而更可靠:
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<title>實用的 js 判斷浏覽器類型及版本</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="JavaScript">
var imyeah = {};
var ua = navigator.userAgent.toLowerCase();
var s;
(s = ua.match(/msie ([\d.]+)/)) ? imyeah.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? imyeah.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? imyeah.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? imyeah.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? imyeah.safari = s[1] : 0;
//以下進行測試
if (imyeah.ie) document.write('IE: ' + imyeah.ie);
if (imyeah.firefox) document.write('Firefox: ' + imyeah.firefox);
if (imyeah.chrome) document.write('Chrome: ' + imyeah.chrome);
if (imyeah.opera) document.write('Opera: ' + imyeah.opera);
if (imyeah.safari) document.write('Safari: ' + imyeah.safari);
</script>
</head>
<body>
</body>
</html>
這段代碼用一串三元運算式串起五次 match,命中哪個就把版本號寫進對應屬性。程式碼雖短,卻能準確分辨 IE、Firefox、Chrome、Opera、Safari 及其版本。
要注意的是,Safari 的判斷必須放在最後並搭配 version/,因為 Chrome 的 userAgent 裡也含有 Safari 字樣,順序錯了就會誤判。
如果今天才要處理這類問題,通常有更好的選擇:用 document.documentElement 上的 class 做特性偵測(Modernizr 就是這個思路),或者在 HTML 標籤上用 IE 條件註解掛上 ie6、ie7 這類 class,再讓 CSS 用選擇器去區分。這種做法把判斷邏輯從 JS 移到 CSS,維護起來清爽很多。