【问题标题】:iFrame - Auto Height on content change within iFrameiFrame - iFrame 内内容更改的自动高度
【发布时间】:2016-06-17 08:30:41
【问题描述】:

我有以下代码:-

<script language="javascript" type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

<div class="resizable">
    <iframe src="http://yellow-taxi.co.uk/onlinebooking/index.php" frameborder="0" width="100%" height="100%" scrolling="no" onload="resizeIframe(this)"></iframe>
</div>

Javascript 会将高度调整为 iFrame 的初始高度,但 iFrame 的高度会随着您完成预订过程而增加。有没有办法根据内容变化自动调整 iFrame 的高度?

注意: iFrame 与 iFrame src 显示在同一域中。

【问题讨论】:

  • 您有任何可用的 javascript 库 (jQuery) 吗?
  • jquery-1.9.1.js

标签: javascript jquery html iframe


【解决方案1】:

长话短说,您不能,除非您的页面与 iframe 页面位于同一域中。您遇到了跨域限制,作为浏览器设置的安全措施,您将无法访问该 iframe 内容中的 JS、DOM 元素或属性。

SO Explanation

【讨论】:

  • iFrame 在同一个域中。
【解决方案2】:

试试这个。不需要 Jquery,但是当内容改变时你必须调用 resizeIframe。

function resizeIframe(obj) {
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight = document.getElementById(obj).contentWindow.document .body.scrollHeight;
        newwidth = document.getElementById(obj).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(obj).height = (newheight) + "px";
    document.getElementById(obj).width = (newwidth) + "px";
}

这是一个示例 iFrame 和其中的必要属性。请务必使用您的 iFrame 名称调用上述方法。

<iframe src="yourpage.htm" width="100%" height="300px" id="yourIframe" marginheight="0" frameborder="0" onLoad="resizeIframe('yourIframe');"></iframe>

还有一个不错的 JQuery 插件可以完成这项任务,据说也可以在域上工作:https://github.com/house9/jquery-iframe-auto-height

【讨论】:

  • 这似乎没有调整任何大小,我在每个函数上都调用它
  • 你怎么称呼它?我将使用我在示例中使用的 iFrame 更新我的答案。
  • 我相信此答案中您的代码的第 1 行缺少 {。
  • 确实有。我更新了答案。谢谢门诺!
猜你喜欢
  • 2022-06-21
  • 2012-09-28
  • 2014-09-29
  • 2013-03-06
  • 1970-01-01
  • 2012-10-29
  • 2012-01-06
  • 2013-08-02
  • 2014-12-25
相关资源
最近更新 更多