【问题标题】:How to adjust the height of an iframe according to the height of its content?如何根据内容的高度调整 iframe 的高度?
【发布时间】:2019-09-15 06:47:57
【问题描述】:

如何根据内容的高度调整 iframe 的高度?我在stackoverflow中阅读了其他答案。但是这些答案对我不起作用。我在 index.html 中有 3 个 iframe。我想调整第二个 id 为 myIframe 的 iframe 的高度。这是我的 index.html(代码在 Internet Explorer 中有效,但在 chrome 和 firefox 中无效):

<!DOCTYPE html>

<html>

<body>

<div style="display: flex; flex-direction: column; align-items: stretch;">

<iframe src="header.html" scrolling="no" style="width: 100%;border: 0; 
height:50px"></iframe>


<iframe class="" id="myIframe" onload = "changeheight()" 
name="a" scrolling="no" style="border:none; width: 100%; min- 
height:calc(100vh - 115px);"  allowtransparency="true" allowfullscreen>

</iframe>

<iframe src="footer.html" scrolling="no" style="width: 100%;border: 0; 
height:50px;"></iframe>


</div>

<script type='text/javascript'>


function changeheight() {

document.getElementById('myIframe').style.height =
document.getElementById('myIframe').contentWindow.document.body.scrollHeight 
+ 'px';
}

</script>


</body>

</html>

而我的 header.html 是

<!DOCTYPE html>

<html>

<body>


<header style="padding: 20px; background: pink">

<a target="a" href="about.html">About us</a>
<a target="a" href="contact.html">Contact us</a>

</header>

</body>

</html>

about.html 和contact.html 包含一些虚拟数据。

我在控制台的 chrome 中收到这两个错误 -

index.html:22 Uncaught ReferenceError: changeheight is not defined
at HTMLIFrameElement.onload (index.html:22)

index.html:82 Uncaught DOMException: Blocked a frame with origin "null" from 
accessing a cross-origin frame.

我不明白为什么我会收到第一个错误。我已经在 javascript 中定义了 changeheight。

我完全不明白第二个错误。

【问题讨论】:

  • 如果托管在同一个域,你可以用JS访问内容,返回它的高度,然后将它设置为iframe。如果是外部的,您必须使用postMessage。但问题是,您是否打算将页面的每个单独部分都设为 iframe?这听起来是个非常糟糕的主意——几乎就像在九十年代使用frameset。有更好的解决方案可以将您的页面编译为一个,您应该尝试不同的策略。 iframe 最适合托管外部内容,而不仅仅是您网站的部分内容...
  • 如果托管在同一个域,你可以用JS访问内容,返回它的高度,然后将它设置为iframe。 - 我这样做了。我已经编写了javascript代码。但它不适用于 chrome 和 firefox。
  • 我被告知只制作一次网站的页眉和页脚。它将在所有页面中使用。我被告知每次创建新页面时不要创建页眉和页脚。
  • 您应该根据浏览器以不同的方式访问内容窗口:stackoverflow.com/questions/926916/… - 但最好只使用fetch 调用来获取页眉和页脚的内容,然后直接添加将它们添加到您的页面,而不是使用 iframe。您还应该考虑可访问性,所有这些框架对于导航到视障人士和使用辅助技术的人来说都是一团糟。

标签: javascript html css iframe flexbox


【解决方案1】:

两个问题

  1. 您需要将脚本移到 iframe 上方

  2. 您需要实际加载一些内容(将 src="someURL" 添加到您尝试使用的 iframe)

see this glitch

【讨论】:

  • 它在故障中工作。但不是在我的电脑里。在我的计算机中,content.html 的内容在底部被截断。
  • 能有css或者flexbox的解决方案吗?
  • 没有 CSS 或 flexbox 解决方案。 99.99% 的网站使用的常规解决方案是在构建时或服务器上运行的模板系统。它们包括每个页面上的header.templatefooter.template。您也可以使用客户端模板,但这意味着阻止 JavaScript 的任何人都无法阅读您的页面。它通常也被认为对 SEO 不利,但如果你愿意,你可以这样做。 Example
猜你喜欢
  • 1970-01-01
  • 2012-08-03
  • 2010-12-18
  • 2012-05-21
  • 2014-11-06
  • 2012-11-19
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
相关资源
最近更新 更多