DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
HTML 文檔類型詳解:標準模式與怪異模式的差異實測
編輯:HTML和Xhtml     

先看兩種常見的文檔類型聲明:

我的寫法:<!DOCTYPE html>

另一種:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

我們發現,JS 在獲取當前頁面可視大小與滾動位置時,兩者存在明顯差異。在一個包含 2000×2000 的 DIV 的頁面中,於 IE 與 Chrome 下分別測試「標準」與「特殊」(未加文檔類型時的預設)模式,整理數據如下:

屬性Chrome 標準Chrome 特殊IE 標準IE 特殊
document.body.clientHeight20006252000604
document.body.scrollTop2242890255
document.body.scrollLeft3153880278
document.body.scrollWidth2005200520052010
document.body.scrollHeight2010201020002005
document.body.offsetHeight200020002000625
document.documentElement.clientHeight62520106040
document.documentElement.scrollTop001990
document.documentElement.scrollLeft002410
document.documentElement.scrollHeight201020102010625
document.documentElement.offsetWidth473473492492
document.documentElement.offsetHeight20102010625625

分析結論:

頁面總寬度: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;
}

補充:可以發現,不同頁面的文檔類型聲明可能並不一致,這正是導致上述差異的根源,值得在開發中特別留意。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved