编辑
//这会得到指定元素的实际width或height
<div id='bodyContent' style="height:600px; width:600px;">
<div style="width:200px; height: 400px; float:left; background-color:pink"></div>
<div style=" margin-left:220px; width:1000px; height:500px; background-color:green; padding:1px;">
<div style="width:200px; height:100px; margin:74px; background-color:lime;"></div>
<div style="width:1200px; height:100px; margin:74px; background-color:lime;">
<!-- Added this element as a check -->
<div style="width:5000px; height:100px; margin:74px; background-color:lime;"></div>
</div>
</div>
</div>
<div id='footerContent' style="min-width:100%; padding:0; background-color:black; height:150px; margin: 100px 0 0 0; position:relative;">
<div id="image" style="width:75px; height:75px; position:absolute; right:37px; bottom: 37px; background-color:yellow;"></div>
</div>
Javascript
//this returns the actual `width` and `height` of the specified element (excluding `borders`)
function getActualWH(el){
return {aW:el.scrollWidth,aH:el.scrollHeight}
}
//如果你想要包含边框的宽度,那么你可以使用我之前的功能之一 ->
function getElProps(el,attr){
//checking if the browser is Internet Explorer
isIEX = navigator.userAgent.match(/Trident/);
whaT_ = isIEX ? el.currentStyle : window.getComputedStyle(el);
getWhaT_ = isIEX ? whaT_.getAttribute(attr) : whaT_.getPropertyValue(attr);
return getWhaT_;
}
示例(无边框):
DEMO
var element = document.getElementById('bodyContent');
width = getActualWH(element).aW;
height = getActualWH(element).aH;
示例(带边框):
DEMO
width = getActualWH(element).aW;
borderLeftWidth = parseInt(getElProps(element,'border-left-width'));
borderRightWidth = parseInt(getElProps(element,'border-right-width'));
actualWidth = width + borderLeftWidth + borderRightWidth;
height = getActualWH(document.getElementById('bodyContent')).aH;
borderTopWidth = parseInt(getElProps(element,'border-top-width'));
borderBottomWidth = parseInt(getElProps(element,'border-bottom-width'));
actualWidth = width + borderTopWidth + borderBottomWidth;
此代码也适用于 IE8(如果您打算支持它)