【问题标题】:Auto height content in an iframe (CORS?)iframe 中的自动高度内容(CORS?)
【发布时间】:2012-10-29 00:28:29
【问题描述】:

我正在与客户合作。他们的网页正在使用这个 DOCTYPE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

我需要向他们网站上的页面提供内容。我的内容是这样的

    <div style="height:1000px">
    <iframe frameborder="0" src="..." width="550" height="220"></iframe>
    <br/>
    <br/>
    <iframe frameborder="0" src="..." width="550" height="220"></iframe>
    </div>

我可以通过给客户几行 css 和当前 iframe 来将内容放在客户页面上:

<style>
.iframecontent
{
    background-color:blue;
    position: relative;
height: 100%;
width: 100%
}
</style>

<iframe class="iframecontent" frameborder="0" src="..." width="100%" scrolling="no"> </iframe>

由于内容的高度是动态的,我无法向客户端提供特定的高度 - 我需要它来拉伸。

我已经阅读了很多帖子,但仍然不确定最好的方法。可能是CORS?还有什么?

这里提供了一个解决方案:http://sly777.github.com/Iframe-Height-Jquery-Plugin/ - 它适用于同一个域,但对于跨域对话,它依赖于 PostMessage,这是一种 HTML 5 的东西。

我尝试了http://blog.johnmckerrell.com/2006/10/22/resizing-iframes-across-domains/,但无法让它工作。

我可能只是让客户端将框架设置为 1500 像素,以便它适合我在内容中选择的任何内容并完成它,但是有更好的方法吗?

【问题讨论】:

    标签: iframe height cors


    【解决方案1】:

    你能设置html,body{height:100%;}然后你的iframe{height:100%}吗?

    百分比高度直接取决于它的父级高度(块元素的)。即:iframe 是什么的 100%?在这种情况下,它的父对象是 body。

    【讨论】:

      【解决方案2】:

      您可以使用 postMessage 插件http://benalman.com/projects/jquery-postmessage-plugin/

      它使您能够将消息从 iframe 内部发布到父元素。结合 setInterval javascript 函数,您可以将当前需要的大小发送到父元素。

      在 iframe 内

      var currentIframeSize = 0; 
      window.setInterval(function() {
          var size = $('body').outerHeight(true);
          //just post, if the size has changed
          if ( currentIframeSize != size ){
              currentIframeSize = size;
              $.postMessage({if_height : size}, source_url, parent);
          }
      }, 1000); //do that every second
      

      在父元素的头部

      id = "theIdOfYourIframe";
      $.receiveMessage(function(e){
          var rec_height = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ) );
          if ( !isNaN( rec_height ) && rec_height > 0 && rec_height !== current_height ) {  
              current_height = rec_height;
              $('#' + id).height(rec_height);
          }
      });
      

      基于这两个 sn-ps,您应该可以解决问题

      【讨论】:

        【解决方案3】:

        我更新了您尝试过的插件 (http://sly777.github.com/Iframe-Height-Jquery-Plugin/),并添加了如何使用此插件进行跨域修复的教程。希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 2016-06-17
          • 2014-09-29
          • 2022-06-21
          • 2013-08-02
          • 2012-09-28
          • 2016-06-13
          • 2015-09-23
          • 2012-12-16
          相关资源
          最近更新 更多