Get height of document content including absolute/

2019-07-05 03:47发布

问题:

I need to resize an iframe to match its content, but the height properties I have tried don't account for elements with position: fixed.

Assume a document with only two elements with the absolute and fixed classes.

body { padding: 0; margin: 0; }
.absolute {
    position: absolute;
    height: 100px;
}
.fixed {
    position: fixed;
    height: 200px;
}
  • html.scrollHeight 0 (viewport height in Opera/Firefox)
  • html.offsetHeight 0
  • body.scrollHeight 0 (viewport height in Chrome)
  • body.offsetHeight 0
  • body.outerHeight 0

If I add html { position: relative; }, html.scrollHeight will be 100px in Chrome, but no value will be 200px. At first I also had an issue with floats, but I solved that by adding a clearfix to body.

I made a jsbin here: http://jsbin.com/ehixiq

If it's not possible to get the real height, what would be my best workaround? I only need to support the latest versions of Opera, Chrome and Firefox.

回答1:

I've found the best way is to use javascript as it can get the height reliably after rendering. In a recent project I did this with jQuery to get full height of the window:

$(document).height()

You could do something like this for element heights:

$('.element2').height($('.element1').height())

Update:

$('iframe').height($('iframe').parent().height())


回答2:

The only way I could figure out was to get the actual bottom position of all elements:

var els = Array.prototype.slice.call(document.body.getElementsByTagName('*'));
var elHeights = [];
for (var i = 0, l = els.length; i < l; i++) {
  elHeights.push(els[i].scrollTop + els[i].offsetHeight);
}
var docHeight = Math.max.apply(Math, elHeights);

Browsers managed between 5-100k operations per second on a DOM with 100 elements, and in my case that's about the size most documents will have.