1、瀏覽器窗口可視區域大小
1.1
對於IE9+、Chrome、Firefox、Opera 以及 Safari:
• window.innerHeight - 瀏覽器窗口的內部高度
• window.innerWidth - 瀏覽器窗口的內部寬度
對於 Internet Explorer 8、7、6、5:
• document.documentElement.clientHeight表示HTML文檔所在窗口的當前高度。
• document.documentElement.clientWidth表示HTML文檔所在窗口的當前寬度。
或者
Document對象的body屬性對應HTML文檔的<body>標簽
• document.body.clientHeight
• document.body.clientWidth
在不同瀏覽器都實用的 JavaScript 方案:
var w= document.documentElement.clientWidth
|| document.body.clientWidth;
var h= document.documentElement.clientHeight
|| document.body.clientHeight;
1.2
針對IE、Opera:
scrollHeight 是網頁內容實際高度,可以小於 clientHeight。
針對NS、FF:
scrollHeight 是網頁內容高度,不過最小值是 clientHeight。也就是說網頁內容實際高度小於 clientHeight 時,scrollHeight 返回 clientHeight 。
瀏覽器兼容性
var w=document.documentElement.scrollWidth
|| document.body.scrollWidth;
var h=document.documentElement.scrollHeight
|| document.body.scrollHeight;
1.3
offsetHeight和offsetWidth,獲取網頁內容高度和寬度(包括滾動條等邊線,會隨窗口的顯示大小改變)。
值
offsetHeight = clientHeight + 滾動條 + 邊框。
瀏覽器兼容性
var w= document.documentElement.offsetWidth
|| document.body.offsetWidth;
var h= document.documentElement.offsetHeight
|| document.body.offsetHeight;
scrollLeft:設置或獲取位於給定對象左邊界與窗口中目前可見內容的最左端之間的距離 ,即左邊灰色的內容。
scrollTop:設置或獲取位於對象最頂端與窗口中可見內容的最頂端之間的距離 ,即上邊灰色的內容。
offsetLeft:獲取指定對象相對於版面或由 offsetParent 屬性指定的父坐標的計算左側位置 。
offsetTop:獲取指定對象相對於版面或由 offsetParent 屬性指定的父坐標的計算頂端位置 。
若是滾動條,拉動滾動條變化的都是scrollLeft、scrollTop
封裝自己的json格式兼容寫法:
1 function client() { 2 if(window.innerWidth != null) // ie9 + 最新瀏覽器 3 { 4 return { 5 width: window.innerWidth, 6 height: window.innerHeight 7 } 8 } 9 else if(document.compatMode === "CSS1Compat") // 標准瀏覽器 10 { 11 return { 12 width: document.documentElement.clientWidth, 13 height: document.documentElement.clientHeight 14 } 15 } 16 return { // 怪異瀏覽器 17 width: document.body.clientWidth, 18 height: document.body.clientHeight 19 20 } 21 }
實例如下:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 9 </body> 10 </html> 11 <script> 12 function client() { 13 if(window.innerWidth != null) // ie9 + 最新瀏覽器 14 { 15 return { 16 width: window.innerWidth, 17 height: window.innerHeight 18 } 19 } 20 else if(document.compatMode === "CSS1Compat") // 標准瀏覽器 21 { 22 return { 23 width: document.documentElement.clientWidth, 24 height: document.documentElement.clientHeight 25 } 26 } 27 return { // 怪異瀏覽器 28 width: document.body.clientWidth, 29 height: document.body.clientHeight 30 31 } 32 } 33 34 document.write(client().width); 35 </script>