不同瀏覽器、不同解析度下的排版需求往往差很多。以下用一小段 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>
var IE1024="" 這幾行的引號中,分別填入「使用者使用 IE,且解析度為 1024×768、800×600、1152×864」時要載入的 CSS 檔名。
var Firefox1024="" 這幾行同理,填入 Firefox 使用者在上述三種解析度下要用的檔名。
var Other1024="" 則是其他瀏覽器對應的檔名。三組都各自準備好,第四個參數(other)就是解析度不符合以上任何一組時的退路。
如果不需要針對解析度分檔,可以簡化成這樣:
<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>
也就是說:IE 載入 default.css、Firefox 載入 default2.css、其他瀏覽器載入 newsky.css。
把整段腳本放在 </head> 之前即可。要注意的是,這種做法只是把差異搬進不同的檔案裡,Hack 並沒有消失;如果能從一開始就用標準語法把樣式寫對,通常比維護好幾份樣式檔輕鬆得多。