如何在给定的URL高度的基础上设置iframe高度

时间:2014-05-09 06:26:35

标签: javascript php html iframe

实际上,我无法根据给定的URL设置动态高度。那时我正在使用下面的代码。

<iframe id="myframe" src="http://example.com" scrolling="yes" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" style="overflow:auto; width:100%; height: 100%;"></iframe>

如果有可能,请建议我解决。

1 个答案:

答案 0 :(得分:1)

您可以通过获取iframe大小并根据其进行调整来实现这一点;

<script type="text/javascript">
  function resizeIframe() {
      var iframe = document.getElementById('myframe');
      if( iframe ) {
            iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
            iframe.width = iframe.contentWindow.document.body.scrollWidth + "px";
      }   
  }
</script> 

在你的框架中;

<iframe id="myframe" src="http://example.com" scrolling="yes" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" onload="resizeIframe()"></iframe>

更新:跨域

如果加载的iframe网址与您的网址不同,则会因CORS而获得权限错误。您需要为您的域授予iframe域的权限。让我们说吧;

iframe域:http://example.com

您的域名:http://yourdomain.com

在Iframe Domain,Apache conf中,您需要在<Directory><Location><Files><VirtualHost&gt;;

中设置标头
Header always append Access-Control-Allow-Origin: "example.com"

如果域名不属于您,则可以使用iframe-resizer。只需添加此库并运行;

iFrameResize();