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

How to set iframe height on the bases of the given URL height

本文关键字:高度 基础上 设置 iframe URL      更新时间:2023-09-26

实际上,我无法根据给定的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>

您可以通过获取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>

Update: Cross Domain

如果加载的iframe url与您的域名不同,您将获得由于CORS的权限错误。您需要为您的域赋予iframe域权限。让说,

Iframe Domain: http://example.com

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

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

Header always append Access-Control-Allow-Origin: "example.com"

如果域不是你的,你可以使用框架调整器。简单地说,添加这个库并运行;

iFrameResize();