您可能必须自己进行性能测试以查看哪种方法最快,但无论如何这里是一种非常快速的方法。(jsfiddle)
function getOuterBoxDimensions() {
var original = document.getElementById('original'),
divs = original.getElementsByTagName('div'),
left = 0,
right = original.offsetWidth,
top = 0,
bottom = original.offsetHeight;
for (var i = 0, div; div = divs[i++];) {
if (div.offsetTop < top) {
top = div.offsetTop;
}
if (div.offsetTop + div.offsetHeight > bottom) {
bottom = div.offsetTop + div.offsetHeight;
}
if (div.offsetLeft < left) {
left = div.offsetLeft;
}
if (div.offsetLeft + div.offsetWidth > right) {
right = div.offsetLeft + div.offsetWidth;
}
}
return {
top: top,
left: left,
bottom: bottom,
right: right
};
// Note that dimensions are relative to the original div top left
}
据我所知,无论是否box-sizing: border-box
设置,offsetLeft、offsetWidth 等都会返回正确的尺寸。如果您在内部 div 中有 div,那么事情会变得有点复杂 - 您只想检查作为原始子节点的 div。
编辑:这是一个扩展版本,它适当地考虑了边距并扩展了新容器以容纳单行中的所有浮动 div(请参阅评论中的讨论)。http://jsfiddle.net/m7N2J/10/
function getOuterBoxDimensions() {
var original = document.getElementById('original'),
divs = original.getElementsByTagName('div'),
left = 0,
right = original.offsetWidth,
top = 0,
bottom = original.offsetHeight,
d = document.defaultView,
style, marginTop, marginBottom, marginLeft, marginRight, float, floatWidth = 0;
for (var i = 0, div; div = divs[i++];) {
if (style = div.currentStyle) {
// May be possible to exclude this if IE7/8 not needed
marginTop = parseFloat(style.marginTop);
marginBottom = parseFloat(style.marginBottom);
marginLeft = parseFloat(style.marginLeft);
marginRight = parseFloat(style.marginRight);
float = style.float;
}
else {
style = d.getComputedStyle(div, null);
marginTop = parseFloat(style.getPropertyValue('margin-top'));
marginBottom = parseFloat(style.getPropertyValue('margin-bottom'));
marginLeft = parseFloat(style.getPropertyValue('margin-left'));
marginRight = parseFloat(style.getPropertyValue('margin-right'));
float = style.getPropertyValue('float');
}
if (float == 'left' || float == 'right') {
floatWidth += div.offsetWidth + marginLeft + marginRight;
if (div.offsetHeight + marginBottom > bottom) {
bottom = div.offsetHeight + marginBottom;
}
}
else {
if (div.offsetTop - marginTop < top) {
top = div.offsetTop - marginTop;
}
if (div.offsetTop + div.offsetHeight + marginBottom > bottom) {
bottom = div.offsetTop + div.offsetHeight + marginBottom;
}
if (div.offsetLeft < left - marginLeft) {
left = div.offsetLeft - marginLeft;
}
if (div.offsetLeft + div.offsetWidth + marginRight > right) {
right = div.offsetLeft + div.offsetWidth + marginRight;
}
}
}
if (right < left + floatWidth) {
right = left + floatWidth;
}
return {
top: top,
left: left,
bottom: bottom,
right: right
};
// Note that dimensions are relative to the original div
}