【问题标题】:Have <iframe> merge with parent body, using only 1 scrollbar for whole page, always adjusting for height让 <iframe> 与父正文合并,整个页面仅使用 1 个滚动条,始终调整高度
【发布时间】:2019-02-03 19:46:30
【问题描述】:

我正在尝试做一些不应该很困难的事情,但令人惊讶的是我无法在网上找到解决方案。

我想将 iframe 嵌入到任何随机网站,而访问者不会注意到它实际上是一个不同的框架。我希望 iframe 与父 body 合并,扩展 parent 的 body,这样网站的 non-iframe-part 和 iframe-part 只能使用父页面的主滚动条滚动。

这是我目前的代码:

<h1>Tours</h1>

<div style="background-color: red; color: white; padding: 200px; text-align: center;">
    Top part of page
</div>

<iframe id="tourtask-iframe" style="overflow: hidden;" src="/public/index.php?b=eit&token=abcd1234&p=tours&lang=en">Please upgrade to a browser that supports iframes.</iframe>

<style>
body, html {
    width: 100%;
    height: 100%;
    margin: 0;
}

#tourtask-iframe {
    width: 100%;
    height: 2000px;
    border: none;
}
</style>

当我在 iframe 存档的源文件正文上执行 overflow: hidden; 时,滚动条消失了,但我无法滚动页面的 iframe 部分。

我需要更新iframe 元素的高度以填充此文件高度的 100%。每当我展开/折叠框架中的任何可折叠内容时,我还需要更新 iframe 元素的高度。

如何做到这一点?或者,还有更好的方法?

我最好不要为父页面使用任何库/框架,因为我需要能够将此 iframe 嵌入到完全不同的网页中。

谢谢!

【问题讨论】:

    标签: javascript html css iframe


    【解决方案1】:

    我为此找到了一个很棒的脚本,称为 iFrame Resizer: https://davidjbradshaw.github.io/iframe-resizer/

    它会感觉到 iframe 源文档高度的任何变化,并相应地更新 iframe 容器。需要进行一些调整和调查才能使其正常工作。

    请确保您遵守以下要求:

    1. iframe 文档必须以 &lt;!DOCTYPE html&gt; 开头。
    2. 确保 iframe 文档的正文不是 100%(例如,使用 Material Design 时默认为 100%)。

    为了成功地将正确调整大小的 iframe 嵌入到父文档中,我现在使用以下代码:

    <iframe id="tourTaskIframe" scrolling="no" src="/public/index.php?b=eit&token=abcd1234&p=tours&lang=en">Please upgrade to a browser that supports iframes.</iframe>
    <script type="text/javascript" src="/public/js/iframeResizer.min.js"></script>
    <script type="text/javascript" src="/public/js/iframeConfig.js"></script>
    <link rel="stylesheet" type="text/css" href="/public/css/iframe-parent.css">
    

    iframeConfig.js:

    iFrameResize({
        heightCalculationMethod : 'bodyOffset'
    }, '#tourTaskIframe');
    

    iframe-parent.css:

    iframe{
        width: 1px;
        min-width: 100%;
        border: none;
    }
    
    body {
        margin: 0;
    }
    

    在 iframe 源文档的 styles.css 中,除了我用于美学的任何其他样式之外,我还有以下基本行:

    body {
        height: auto !important; /* Essential for resizing */
        min-height: 0 !important; /* Essential for resizing */  
    }
    

    就是这样!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 2012-10-16
      • 2012-08-19
      • 2014-03-16
      相关资源
      最近更新 更多