推荐关注
› Meteor
› JSLint - a JavaScript code quality tool
› jsFiddle
› D3.js
› WebStorm
推荐书目
› JavaScript 权威指南第 5 版
› Closure: The Definitive Guide
rogwan

JavaScript 如何控制 iframe 子页面自适应高度?

  •  
  •   rogwan · May 4, 2017 · 4905 views
    This topic created in 3483 days ago, the information mentioned may be changed or developed.

    在 A 网站的页面中,用 iframe 嵌入一个来自 B 网站的子页面,怎么控制 iframe 子页面自适应高度?

    比如,在 A 网站的 index.html 中,用 iframe 嵌入一个 B 网站的 child.html 子页面:

    <iframe id="iframe_id" height=100% width=100% src="http://B.com/child.html" scrolling="no" frameborder=0></iframe>
    

    (由于 child.html 是动态高度的)然后在上面这段代码下面,添加 JavaScript 来修改 iframe 高度:

    <script type="text/javascript">
        var x = document.getElementById("iframe_id");
        x.height=document.documentElement.clientHeight;
    </script>
    

    修改 iframe 的高度之后,child.html 页面下半截还是被遮住(显示不完全)。把 clientHeight 改成 scrollHeight 也一样不能完全显示 child.html 的全部高度。

    7 replies  •  2017-05-05 09:17:18 +08:00
    hjdtl
    hjdtl
    May 4, 2017
    1
    把 overflow 设置为 scroll 试一下
    J0k3r
    J0k3r
    May 4, 2017
    2
    <iframe width="100%" border="0" marginwidth="0" marginheight="0" frameborder="0" scrolling="no"
    src="http://B.com/child.html" onload="this.height=document.documentElement.clientHeight">
    </iframe>
    rogwan
    rogwan
    OP
    May 4, 2017
    3
    @hjdtl
    @J0k3r
    建议的方法是不是只能在同一个域名的前提下在能生效?

    我在两个不同域名之间 A 网站的 index.html 页面,用 iframe 嵌入了 B 网站 的 child.html 子页面,发现就不能起作用了?
    yoonper
    yoonper
    May 4, 2017 via iPhone
    4
    跨域 IFRAME 自适应高度
    http://www.yoonper.com/post.php?id=26
    beginor
    beginor
    May 5, 2017 via Android
    5
    @yoonper 👍
    Kokororin
    Kokororin
    May 5, 2017 via iPhone
    6
    window.postMessage
    J0k3r
    J0k3r
    May 5, 2017
    7
    @rogwan 你试试我给你的方法,应该可以的,我一直就这么用的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2443 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 05:02 · PVG 13:02 · LAX 21:02 · JFK 00:02
    ♥ Do have faith in what you're doing.