设置 iframe 内容高度以动态自动调整大小
我自己正在寻找一个简单的解决方案来更改 iframe 及其内容的高度。
似乎规则是您无法从包含 iframe 的页面获取 iframe 的高度。这显然是出于安全考虑。我们怎样才能做到这一点?
I was myself searching for a simple solution to change the height of an iframe with the content in it.
It seems like the rules are that you can't get the height of the iframe from the page holding it. This is because of security apparently. How can we do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 iframe 中:
这意味着您必须在 iframe 页面中添加一些代码。
只需将此脚本添加到 IFRAME 中的代码中即可:
在保留页面中:
在包含 iframe 的页面中(在我的例子中 ID="myiframe")添加一个小的 javascript:
现在发生的情况是,当加载 iframe 时,它会在父窗口中触发一个 javascript,在本例中是包含 iframe 的页面iframe。
它向该 JavaScript 函数发送其 (iframe) 高度的像素数。
父窗口获取该数字,添加 32 以避免出现滚动条,并将 iframe 高度设置为新数字。
就这样,不需要其他的了。
但如果您想了解更多小技巧,请继续阅读...
IFRAME 中的动态高度?
如果您像我一样喜欢切换内容,iframe 高度将会改变(无需重新加载页面并触发加载)。
我通常添加一个我在网上找到的非常简单的切换脚本:
在该脚本中只需添加:
如何使用上面的脚本很简单:
对于那些喜欢剪切和粘贴并从那里开始的人来说,这里是两个页面。就我而言,我将它们放在同一个文件夹中,但它也应该跨域工作(我认为...)
完整的保留页面代码:
完整的 iframe 代码:(这iframe 名为“theiframe.htm”)
演示
In the iframe:
So that means you have to add some code in the iframe page.
Simply add this script to your code IN THE IFRAME:
In the holding page:
In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME?
If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload).
I usually add a very simple toggle script I found online:
to that script just add:
How you use the above script is easy:
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
Complete iframe code: (this iframe named "theiframe.htm")
Demo
简单的解决方案:
当 iframe 和父窗口位于同一域中时,此方法有效。当两者处于不同域时,它不起作用。
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.