javascript - 通过获取 scrollHeight (javascript) 调整 iFrame 的大小以适应内容

标签 javascript iframe

我正在尝试调整 iframe 的大小以适应内容。在看到其他人是如何做到的之后,我认为最简单的方法是获取 iframe 的 scrollHeight 并相应地调整 iframe 的大小。我在 iframe 标记中使用 onload 来运行它。我已经根据这个主题创作了数十种变体,但都没有成功。

 function resizeIFrame(){

     var sHeight, frame;

      frame = document.getElementById("bigFrame");
      sHeight = frame.scrollHeight;
      frame.style.height = sHeight + 'px';
    }

当我警告 sHeight 变量时,我得到的是框架的高度,而不是 scrollHeight。这表明我可能没有正确收集 scrollHeight。

我知道这个问题可能与之前的许多问题类似,但是有很多方法可以解决这个问题,而且答案也多种多样。我想知道这种调整 iframe 大小以适应内容的方法有什么问题?

这是html。

   <div id="contentContainer">
       <iframe id="bigFrame" 
                src="home/home.html" 
                name="mainFrame"     
                onload="resizeIFrame()" 
                onresize="resizeIFrame()" 
                scrolling="no" 
                seamless;  >
            </iframe>
   </div>

最佳答案

好的,我让它完美地工作了。
添加 - contentWindow.document.body.scrollHeight - 使我能够获得 scrollHeight。我试图从变量中获取 scrollHeight。这没有用。有效的方法是直接从文档中获取 scrollHeight。

我不得不在每一页的底部添加一些空间。因此+80;。不幸的是,每次调用该函数时,这只会增加 80。在重新调整之前将框架高度重置为 0px 解决了这个问题。

就这样吧。此函数通过获取 scrollHeight 并设置 iframe 高度以匹配来调整 iframe 的大小以适合其内容。

 function resizeIFrame(){

        var sHeight, frame;

           frame = document.getElementById("bigFrame");
           frame.style.height = '0px';
           sHeight = document.getElementById('bigFrame').
                  contentWindow.document.body.scrollHeight + 80;
           frame.style.height = sHeight + 'px';
     }

关于javascript - 通过获取 scrollHeight (javascript) 调整 iFrame 的大小以适应内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34023681/

相关文章:

javascript - wrapper 在 Firebug 中是什么意思?

php - 嵌入式 iframe - 验证 GET 请求的来源/来源

iframe - 如何阻止YouTube iframe嵌入自动播放

javascript - iframe 内 Web 元素的 QuerySelector

javascript - 动态 iframe 链接

javascript - 是否可以从 javascript 访问 SMIL 计时器?

javascript - Node-Red 发送二进制文件

javascript - 浏览器希望用户在按第二页上的后退按钮时重新提交/刷新第一页

html - Facebook 点赞按钮的 iframe

javascript - JavaScript 中的可选链接