做 iframe 自適應、固定 header、計算滾動比例等功能時,取得頁面尺寸是基本工課。麻煩的是不同瀏覽器與不同模式(標準/怪異)取值的來源並不一致。
BackCompat:標準模式關閉,也就是 quirks(怪異)模式。CSS1Compat:標準模式開啟。判斷方式是讀取 document.compatMode。
一般情況下 window.innerHeight 就能取得;標準模式下若 document.documentElement.clientHeight 可用,它就是可視區域高度;怪異模式下則要改用 document.body.clientHeight。
function getViewportWH() {
var wh = {};
"Height Width".replace(/[^\s]+/g, function(a) {
var b = a.toLowerCase();
wh[b] = window["inner" + a]
|| (document.compatMode === "CSS1Compat"
? document.documentElement["client" + a]
: document.body["client" + a]);
});
return wh;
}
用於 iframe 自適應時,需要的是文檔的 scrollHeight 而非可視高度:
function getDocWH() {
var wh = {};
"Height Width".replace(/[^\s]+/g, function(a) {
var b = a.toLowerCase();
wh[b] = document.compatMode === "CSS1Compat"
? document.documentElement["scroll" + a]
: document.body["scroll" + a];
});
return wh;
}
這裡有個額外的坑:webkit 內核的瀏覽器即使處於標準模式,在部分情況下也是以 body 承載捲動,因此判斷條件與上面兩個函式不同。
var scrollUtil = {};
scrollUtil.scrollTopFn = function(arg) {
var isWebkit = navigator.userAgent.toLowerCase().indexOf("webkit") > -1;
if (isWebkit || document.compatMode === "BackCompat") {
this.scrollTopFn = function(arg) {
if (typeof arg === 'number') { document.body.scrollTop = arg; }
else { return document.body.scrollTop; }
};
} else {
this.scrollTopFn = function(arg) {
if (typeof arg === 'number') { document.documentElement.scrollTop = arg; }
else { return document.documentElement.scrollTop; }
};
}
return this.scrollTopFn.apply(this, arguments);
};
這裡用了一個小技巧:第一次呼叫時完成判斷並重新定義自己,後續呼叫就不必再跑一次條件判斷,等於做了 lazily 的快取。
這些判斷在當年確實得一個個試出來,但現在已經有更好的選擇。查詢尺寸時直接用 document.documentElement.clientWidth(永遠指可視區域)與 document.documentElement.scrollHeight;查捲動量則統一用 window.pageYOffset,跨瀏覽器一致且不必判斷 compatMode。
另外,navigator.userAgent 判斷內核是應該避免的做法——使用者代理字串可被偽造、也會隨版本漂移。要偵測功能,請用 typeof window.visualViewport !== 'undefined' 這類特性偵測,或直接省略判斷改用標準 API。