document.compatMode用來判斷當前瀏覽器採用的渲染方式。
document.compatMode屬性值:瀏覽器
BackCompat:標準兼容模式關閉。
CSS1Compat:標準兼容模式開啓。
當document.compatMode等於BackCompat時,瀏覽器客戶區寬度是document.body.clientWidth;
當document.compatMode等於CSS1Compat時,瀏覽器客戶區寬度是document.documentElement.clientWidth。
瀏覽器客戶區高度(clientHeight)、滾動條高度(scrollHeight)、滾動條的Left(scrollLeft)、滾動條的Top(scrollTop)等等都是上面的狀況。
下面是demo:準確獲取網頁客戶區的寬高、滾動條寬高、滾動條Left和Top的代碼:
if (document.compatMode == \"BackCompat\") {
cWidth = document.body.clientWidth;
cHeight = document.body.clientHeight;//瀏覽器客戶區高度
sWidth = document.body.scrollWidth;
sHeight = document.body.scrollHeight;//滾動條高度
sLeft = document.body.scrollLeft;//滾動條的Left
sTop = document.body.scrollTop;//滾動條的Top
}
else { //document.compatMode == \"CSS1Compat\"
cWidth = document.documentElement.clientWidth;
cHeight = document.documentElement.clientHeight;
sWidth = document.documentElement.scrollWidth;
sHeight = document.documentElement.scrollHeight;
sLeft = document.documentElement.scrollLeft == 0 ? document.body.scrollLeft : document.documentElement.scrollLeft;
sTop = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
}spa
簡單點來講:
var pageWidth=window.innerWidth,
pageHeight=window.innerHeight;
if(typeof pageWidth!='number'){
if(document.compatMode=='CSS1Compat'){
pageWidth=document.documentElement.clientWidth;
pageHeight=document.documentElement.clientHeight;
}
else{
pageWidth=document.body.clientWidth;
pageHeight=document.body.clientHeight;
}
}
(以上代碼兼容目前流行的所有瀏覽器,包括:IE、Firefox、Safari、Opera、Chrome)cli