获取文档内容的高度,包括绝对/固定定位元素 [英] Get height of document content including absolute/fixed positioned elements

查看:676
本文介绍了获取文档内容的高度,包括绝对/固定定位元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调整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.

      这篇关于获取文档内容的高度,包括绝对/固定定位元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆