JavaScript 如何控制 iframe 子页面自适应高度?

2017-05-04 14:54:32 +08:00
 rogwan

在 A 网站的页面中,用 iframe 嵌入一个来自 B 网站的子页面,怎么控制 iframe 子页面自适应高度?

比如,在 A 网站的 index.html 中,用 iframe 嵌入一个 B 网站的 child.html 子页面:

<iframe id="iframe_id" height=100% width=100% src="http://B.com/child.html" scrolling="no" frameborder=0></iframe>

(由于 child.html 是动态高度的)然后在上面这段代码下面,添加 JavaScript 来修改 iframe 高度:

<script type="text/javascript">
    var x = document.getElementById("iframe_id");
    x.height=document.documentElement.clientHeight;
</script>

修改 iframe 的高度之后,child.html 页面下半截还是被遮住(显示不完全)。把 clientHeight 改成 scrollHeight 也一样不能完全显示 child.html 的全部高度。

3698 次点击
所在节点    JavaScript
7 条回复
hjdtl
2017-05-04 15:02:09 +08:00
把 overflow 设置为 scroll 试一下
J0k3r
2017-05-04 15:16:00 +08:00
<iframe width="100%" border="0" marginwidth="0" marginheight="0" frameborder="0" scrolling="no"
src="http://B.com/child.html" onload="this.height=document.documentElement.clientHeight">
</iframe>
rogwan
2017-05-04 21:10:14 +08:00
@hjdtl
@J0k3r
建议的方法是不是只能在同一个域名的前提下在能生效?

我在两个不同域名之间 A 网站的 index.html 页面,用 iframe 嵌入了 B 网站 的 child.html 子页面,发现就不能起作用了?
yoonper
2017-05-04 23:34:23 +08:00
跨域 IFRAME 自适应高度
http://www.yoonper.com/post.php?id=26
beginor
2017-05-05 06:49:03 +08:00
@yoonper 👍
Kokororin
2017-05-05 07:13:09 +08:00
window.postMessage
J0k3r
2017-05-05 09:17:18 +08:00
@rogwan 你试试我给你的方法,应该可以的,我一直就这么用的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/359085

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX