不同解析度、不同瀏覽器對同一套樣式的詮釋落差,有時候大到必須分開處理。以下用 JavaScript 動態改寫 <link> 的 href,來達到「依環境載入不同樣式表」的效果。
<SCRIPT LANGUAGE="javascript">
<!--
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
var IE1024 = "";
var IE800 = "";
var IE1152 = "";
var IEother = "";
ScreenWidth(IE1024, IE800, IE1152, IEother);
} else {
if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
var Firefox1024 = "";
var Firefox800 = "";
var Firefox1152 = "";
var Firefoxother = "";
ScreenWidth(Firefox1024, Firefox800, Firefox1152, Firefoxother);
} else {
var Other1024 = "";
var Other800 = "";
var Other1152 = "";
var Otherother = "";
ScreenWidth(Other1024, Other800, Other1152, Otherother);
}
}
function ScreenWidth(CSS1, CSS2, CSS3, CSS4) {
if ((screen.width == 1024) && (screen.height == 768)) {
setActiveStyleSheet(CSS1);
} else {
if ((screen.width == 800) && (screen.height == 600)) {
setActiveStyleSheet(CSS2);
} else {
if ((screen.width == 1152) && (screen.height == 864)) {
setActiveStyleSheet(CSS3);
} else {
setActiveStyleSheet(CSS4);
}
}
}
}
function setActiveStyleSheet(title) {
document.getElementsByTagName("link")[0].href = "style/" + title;
}
//-->
</SCRIPT>
IE1024 / IE800 / IE1152 / IEother:使用者用 IE,且解析度分別為 1024×768、800×600、1152×864 時要載入的 CSS 檔名,其他情況則用 IEother。Firefox1024 / Firefox800 / Firefox1152 / Firefoxother:使用者用 Firefox 時的對應檔名。Other1024 / Other800 / Other1152 / Otherother:其他瀏覽器的對應檔名。<SCRIPT LANGUAGE="javascript">
<!--
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
setActiveStyleSheet("default.css"); // IE
} else {
if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
setActiveStyleSheet("default2.css"); // Firefox
} else {
setActiveStyleSheet("newsky.css"); // 其他
}
}
function setActiveStyleSheet(title) {
document.getElementsByTagName("link")[0].href = "style/" + title;
}
//-->
</SCRIPT>
用法:放在 <head></head> 之間即可。
這個做法在當年是常見手段,但以今天的角度看有幾個明確缺陷:
screen.width 卻仍回報 1920。link[0] 太脆弱。只要 head 裡多一個 link 標籤(例如 favicon),就會指錯檔案。現在完全不需要為不同環境準備不同 CSS 檔:
/* 依視窗寬度自動切換,不必寫 JavaScript */
.container { width: 90%; max-width: 1200px; margin: 0 auto; }
@media (max-width: 768px) {
.sidebar { display: none; }
}
再搭配:
%、rem、vw、clamp() 取代寫死的 pxmax-width 限制內容不無限拉寬<meta name="viewport" content="width=device-width, initial-scale=1"> 讓行動裝置正確縮放<picture>、srcset 依裝置載入合適尺寸核心觀念的轉變是:不要猜使用者的環境,而是讓版面自己適應任何環境。這比維護十份樣式表都輕鬆。