先看兩種常見的文檔類型聲明:
我的寫法:<!DOCTYPE html>
另一種:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
我們發現,JS 在獲取當前頁面可視大小與滾動位置時,兩者存在明顯差異。在一個包含 2000×2000 的 DIV 的頁面中,於 IE 與 Chrome 下分別測試「標準」與「特殊」(未加文檔類型時的預設)模式,整理數據如下:
| 屬性 | Chrome 標準 | Chrome 特殊 | IE 標準 | IE 特殊 |
|---|---|---|---|---|
| document.body.clientHeight | 2000 | 625 | 2000 | 604 |
| document.body.scrollTop | 224 | 289 | 0 | 255 |
| document.body.scrollLeft | 315 | 388 | 0 | 278 |
| document.body.scrollWidth | 2005 | 2005 | 2005 | 2010 |
| document.body.scrollHeight | 2010 | 2010 | 2000 | 2005 |
| document.body.offsetHeight | 2000 | 2000 | 2000 | 625 |
| document.documentElement.clientHeight | 625 | 2010 | 604 | 0 |
| document.documentElement.scrollTop | 0 | 0 | 199 | 0 |
| document.documentElement.scrollLeft | 0 | 0 | 241 | 0 |
| document.documentElement.scrollHeight | 2010 | 2010 | 2010 | 625 |
| document.documentElement.offsetWidth | 473 | 473 | 492 | 492 |
| document.documentElement.offsetHeight | 2010 | 2010 | 625 | 625 |
分析結論:
頁面總寬度:document.body.scrollWidth;
頁面總高度:document.body.scrollHeight;
Chrome 頁面位置:document.body.scrollTop、document.body.scrollLeft;
Chrome 標準模式可視區域:document.documentElement.clientWidth、clientHeight;
Chrome 特殊模式可視區域:document.body.clientWidth、clientHeight;
IE 標準模式位置與可視區域:均取 document.documentElement 的 scrollTop/scrollLeft 與 clientWidth/clientHeight;
IE 特殊模式位置與可視區域:均取 document.body 的 scrollTop/scrollLeft 與 clientWidth/clientHeight。
相容處理的 JS 代碼如下:
function getSize() {
var obj = new Object();
obj.allWidth = document.body.scrollWidth;
obj.allHeight = document.body.scrollHeight;
if (-[1, ]) { //非IE
obj.top = document.body.scrollTop;
obj.left = document.body.scrollLeft;
if (document.compatMode === 'CSS1Compat') {
obj.width = document.documentElement.clientWidth;
obj.height = document.documentElement.clientHeight;
}
else {
obj.width = document.body.clientWidth;
obj.height = document.body.clientHeight;
}
} else {
if (document.compatMode === 'CSS1Compat') {
obj.width = document.documentElement.clientWidth;
obj.height = document.documentElement.clientHeight;
obj.top = document.documentElement.scrollTop;
obj.left = document.documentElement.scrollLeft;
}
else {
obj.width = document.body.clientWidth;
obj.height = document.body.clientHeight;
obj.top = document.body.scrollTop;
obj.left = document.body.scrollLeft;
}
}
alert(obj.top);
alert(obj.left);
alert(obj.width);
alert(obj.height);
return obj;
}補充:可以發現,不同頁面的文檔類型聲明可能並不一致,這正是導致上述差異的根源,值得在開發中特別留意。