获取文档内容的高度,包括绝对/固定定位元素
我需要调整iframe的大小以匹配其内容,但我尝试的高度属性不考虑 position:fixed
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
.
假设一个文档只有两个元素, absolute
和 code> classes。
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(Opera / Firefox中的视口高度) -
html.offsetHeight
0 $ b -
body.scrollHeight
0(Chrome浏览器高度) -
body.offsetHeight 0
-
html.scrollHeight
0 (viewport height in Opera/Firefox) -
html.offsetHeight
0 -
body.scrollHeight
0 (viewport height in Chrome) -
body.offsetHeight
0 -
body.outerHeight
0
如果我添加 html {position:relative; }
, html.scrollHeight
在Chrome中为100像素,但没有值为200像素。起初我也有一个浮动问题,但我解决了,通过添加一个clearfix到 body
。
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
.
在这里制作了一个jsbin: http://jsbin.com/ehixiq
I made a jsbin here: http://jsbin.com/ehixiq
如果不可能得到真实的高度,我最好的解决方法是什么?我只需要支持最新版本的Opera,Chrome和Firefox。
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.
我能想出的唯一方法是所有元素的实际底部位置:
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);
浏览器在一个有100个元素的DOM上每秒管理5-10万次操作,在我的例子中关于大多数文件的大小。
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.