
js中clientWidth, scrollWidth, innerWidth, outerWidth,offsetWidth的屬性匯總,測試瀏覽器:ie7~ie11、chrome 和 firefox等。

一、測試1:無滾動條時,dom對象的offsetWidth、clientWidth和scrollWidth
(1)測試代碼
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<title>Javascript</title>
<style>
*{margin: 0;padding: 0;}
body{font: 12px/2 Arial;background-color: #ccc;padding: 20px;}
#b1{width: 530px;height: 320px;background-color: #fff;position: relative;}
#b2{width: 220px;height: 130px;background-color: orange;border: 10px solid #085A90;padding: 10px;position: relative;left: 140px;top: 90px;}
</style>
</head>
<body>
<div id="b1"><div id="b2"></div></div>
<script>
window.onload = function(){
var oB2 = document.getElementById('b2');
console.log("offsetWidth="+oB2.offsetWidth, "offsetHeight="+oB2.offsetHeight);
console.log("clientWidth="+oB2.clientWidth, "clientHeight="+oB2.clientHeight);
console.log("offsetLeft="+oB2.offsetLeft, "offsetTop="+oB2.offsetTop);
console.log("scrollWidth="+oB2.scrollWidth, "scrollHeight="+oB2.scrollHeight);
console.log("scrollLeft="+oB2.scrollLeft, "scrollTop="+oB2.scrollTop);
}
</script>
</body>
</html>
(2)測試結果

IE7下,scrollWidth = 20,scrollHeight = 34
(3)圖解結果

二、測試2:有滾動條時,dom對象offsetWidth、clientWidth 和 scrollWidth
(1)測試代碼
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<title>Javascript</title>
<style>
*{margin: 0;padding: 0;}
body{font: 12px/2 Arial;background-color: #ccc;padding: 20px;}
#b1{width: 300px;height: 220px;background-color: #fff;position: relative;overflow: auto;border: 10px solid #999;padding: 10px;}
#b2{width: 220px;height: 330px;background-color: orange;border: 10px solid #085A90;padding: 10px;position: relative;left: 140px;top: 90px;}
</style>
</head>
<body>
<div id="b1"><div id="b2"></div></div>
<script>
window.onload = function(){
var oB1 = document.getElementById('b1');
console.log("offsetWidth="+oB1.offsetWidth, "offsetHeight="+oB1.offsetHeight);
console.log("clientWidth="+oB1.clientWidth, "clientHeight="+oB1.clientHeight);
console.log("offsetLeft="+oB1.offsetLeft, "offsetTop="+oB1.offsetTop);
console.log("scrollWidth="+oB1.scrollWidth, "scrollHeight="+oB1.scrollHeight);
console.log("scrollLeft="+oB1.scrollLeft, "scrollTop="+oB1.scrollTop);
}
</script>
</body>
</html>
(2)測試結果
這里我們需要讀取外層帶滾動條的 div#b1 的值。ie7~ie11、chrome 和 firefox 結果一致,如下:

(3)圖解結果

三、測試3:window對象的 outerWidth、innerWidth、pageXOffset 和 screenLeft(screenX)
(1)測試代碼
<script> window.onload = function(){ console.log("innerWidth="+window.innerWidth, "innerHeight=" + window.innerHeight); console.log("outerWidth="+window.outerWidth, "outerHeight=" + window.outerHeight); console.log("pageXOffset="+window.pageXOffset, "pageYOffset=" + window.pageYOffset); console.log("screenX="+window.screenX, "screenY=" + window.screenY); console.log("screenLeft="+window.screenLeft, "screenTop=" + window.screenTop); } </script>
(2)圖解結果(不同瀏覽器下,console 輸出與下圖部分有不同)

