【问题标题】:change iframe height according to content根据内容更改 iframe 高度
【发布时间】:2013-03-06 11:28:18
【问题描述】:

iframe 标签:

  <iframe scrolling="no" style="height: 956px; width: 100%" frameborder="0" id="ampcontentiframe"></iframe>

我正在尝试调整内容加载时 iframe 的高度。我尝试了其他解决方案:

Link1

Link2

Link3

但它们都没有解决我的问题。我尝试在窗口加载和 iframe 加载时调用 resize 函数。但是它每次设置的高度都不同(有时是实际内容高度,有时是 iframe 的原始高度)。

任何帮助......??

仅供参考:我也尝试从 iframe 中删除滚动属性。但它不起作用

【问题讨论】:

    标签: javascript jquery css iframe


    【解决方案1】:

    这是真正比它应该更难的问题之一。以下是您需要考虑的事项,以保持 iFrame 的大小正确。

    计算出准确的高度

    获取 iFrame 的准确高度并不像应有的那么简单,因为您可以选择六种不同的属性来检查它们,但它们都不能给出始终正确的答案。我想出的最好的解决方案是这个函数,只要你不使用 CSS 溢出 body 标签就可以工作。

    function getIFrameHeight(){
        function getComputedBodyStyle(prop) {
            return parseInt(
                document.defaultView.getComputedStyle(document.body, null),
                10
            );
        }
    
        return document.body.offsetHeight +
            getComputedBodyStyle('marginTop') +
            getComputedBodyStyle('marginBottom');
    }
    

    这是 IE9 版本,更多长的 IE8 版本见answer

    如果您确实溢出了正文并且您无法修复您的代码来阻止它,那么使用document.documentElementoffsetHeightscrollHeight 属性是您的最佳选择。两者各有利弊,最好只是测试一下,看看哪个适合你。

    留言

    postMessage API 提供了一种在 iFrame 与其父级之间进行通信的简单方法。

    要向父页面发送消息,请按如下方式调用它。

    parent.postMessage('Hello parent','http://origin-domain.com');
    

    在另一个方向,我们可以使用以下代码将消息发送到 iFrame。

    var iframe = document.querySelector('iframe');
    iframe.contentWindow.postMessage('Hello my child', 'http://remote-domain.com:8080');
    

    要接收消息,请为消息事件创建事件侦听器。

    function receiveMessage(event)
    {
      if (event.origin !== "http://remote-domain.com:8080")
        return;
    
      console.log(event.data);
    }
    
    if ('addEventListener' in window){
        window.addEventListener('message', receiveMessage, false);
    } else if ('attachEvent' in window){ //IE
        window.attachEvent('onmessage', receiveMessage);
    

    这些示例使用 origin 属性来限制消息发送到哪里并检查它来自哪里。可以指定* 以允许发送到任何域,并且在某些情况下您可能希望接受来自任何域的消息。但是,如果您这样做,您需要考虑安全隐患并对传入消息实施您自己的检查,以确保它包含您所期望的内容。在这种情况下,iframe 可以将其高度发布到“*”,因为我们可能有多个父域。但是,检查传入消息是否来自 iFrame 是个好主意。

    function isMessageFromIFrame(event,iframe){
        var
            origin  = event.origin,
            src     = iframe.src;
    
        if ((''+origin !== 'null') && (origin !== src.substr(0,origin.length))) {
            throw new Error(
                'Unexpect message received from: ' + origin +
                ' for ' + iframe.id + '. Message was: ' + event.data  
            );
        }
    
        return true;
    }
    

    变异观察者

    更现代的浏览器的另一个进步是MutationObserver,它允许您观察 DOM 的变化;因此现在可以检测可能影响 iFrame 大小的更改,而无需使用 setInterval 不断轮询。

    function createMutationObserver(){
        var
            target = document.querySelector('body'),
    
            config = {
                attributes            : true,
                attributeOldValue     : false,
                characterData         : true,
                characterDataOldValue : false,
                childList             : true,
                subtree               : true
            },
    
            observer = new MutationObserver(function(mutations) {
                parent.postMessage('[iframeResize]'+document.body.offsetHeight,'*');
            });
    
        log('Setup MutationObserver');
        observer.observe(target, config);
    }
    
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
    
    if (MutationObserver){
        createMutationObserver();
    }
    

    其他问题

    需要考虑的其他事项包括,页面上有多个 iFrame,CSS :Checkbox 和 :Hover 事件导致页面调整大小,避免在 iFrame 的 body 和 html 标记中使用 height auto,最后调整窗口大小。

    IFrame 调整器库

    我将所有这些都封装在一个简单的无依赖库中,该库还提供了一些此处未讨论的额外功能。

    https://github.com/davidjbradshaw/iframe-resizer

    这适用于 IE8+。

    【讨论】:

      【解决方案2】:

      你可以试试下面的脚本。

      <script type="text/javascript">
        function iframeLoaded() {
          var iFrameID = document.getElementById('your_frame_id');
          if(iFrameID) {            
              iFrameID.height = "";
              iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
         }   
      }
      </script> 
      

      并将 onload 函数添加到您的 iframe 中,例如

      <iframe onload="iframeLoaded()">
      

      【讨论】:

        【解决方案3】:

        如果你想为 iframe 滚动条试试这个

        <iframe style="height: 956px;overflow-y:scroll; width: 100%" frameborder="0" id="ampcontentiframe"></iframe>
        

        只需输入“min-height”并添加“overflow-y”道具作为滚动它就会起作用

        或者如果你不想滚动,那么试试

        <iframe scrolling="no" style="min-height: 956px; width: 100%" frameborder="0" id="ampcontentiframe"></iframe>
        

        【讨论】:

        • 只考虑两个建议
        猜你喜欢
        • 2012-09-28
        • 2012-01-06
        • 2012-08-03
        • 2010-12-18
        • 1970-01-01
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 2011-11-17
        相关资源
        最近更新 更多