不同解析度需要不同的版面配置時,可以透過 JavaScript 偵測環境,動態更換樣式表的路徑。以下示範兩種做法。(本文程式碼來自網路分享,使用前請自行驗證。)
<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> 區塊中即可。IE 載入 default.css,Firefox 載入 default2.css,其餘載入 newsky.css。
先為三種環境各預留四個變數,分別對應 1024×768、800×600、1152×864 與其他解析度:
<script language="javascript">
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
var IE1024 = "", IE800 = "", IE1152 = "", IEother = "";
ScreenWidth(IE1024, IE800, IE1152, IEother);
} else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
var FF1024 = "", FF800 = "", FF1152 = "", FFother = "";
ScreenWidth(FF1024, FF800, FF1152, FFother);
} else {
var Other1024 = "", Other800 = "", Other1152 = "", 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>
把各變數的引號中填入對應的 CSS 檔名即可。
UA 偵測不可靠。使用者代理字串可以被偽造,且瀏覽器版本迭代後判斷條件就會失效。判斷瀏覽器型別來切換樣式,本質上是在猜,而不是在處理真正該處理的問題。
screen.width 是螢幕寬度,不是視窗寬度。它不會隨視窗縮放改變,使用者把視窗縮小時版面不會跟著調整。應改用 window.innerWidth 才符合需求。
這個需求現在完全不需要 JavaScript,用 CSS 媒體查詢就能處理,而且會隨視窗尺寸即時響應:
/* 預設樣式,適用於所有尺寸 */
.container { width: 100%; }
/* 800px 以下 */
@media (max-width: 800px) {
.container { padding: 8px; }
}
/* 1024px 以上 */
@media (min-width: 1024px) {
.container { width: 960px; margin: 0 auto; }
}
至於跨瀏覽器的樣式差異,也請優先用標準語法搭配 @supports 功能偵測來處理,而不是靠 UA 字串分流。動態切換主題(例如深淺色模式)若要保留,用 prefers-color-scheme 媒體查詢會比 JS 更簡潔可靠。