我正在尝试在 Drupal 页面上包含一个 iframe
。到目前为止,我成功地包含了框架,但我编写的高度调整功能只能在 Internet Explorer 中使用。我的目标是让调整大小在 Firefox 和 Chrome 中也能正常工作。我在 Internet 上进行了搜索,但找不到我要找的东西。长话短说,我希望我的框架能够自动调整高度。
这是我目前所做的(这是 Drupal 中包含的 HTML 页面的代码):
<script type="text/javascript">
function resize() {
var iframe = document.all.icw;
document.getElementById("icw").style.height = iframe.document.body.scrollHeight + "px";
}
</script>
<iframe id="icw" src="XXXXX" width="100%" scrolling="no" onload="resize()">
我知道如果 iframe
存在于另一个域中,由于权限的原因,解决方案可能会更加困难。对吗?
这些是我在 Chrome 和 Firefox 中遇到的错误:
Chrome: Cannot read property 'body' of undefined
Chrome: JavaScript attempt to access frame with URL XXX from frame with URL YYY. Domains, protocols and ports must match.
Firefox: document.all is undefined
编辑:如果我想更改其中一个 iframe
元素怎么办?就我而言,我需要更改文本框值。我知道我必须在加载页面时这样做,但我找不到解决方案。无论我把代码放在哪里,我总是得到一个
Cannot call method 'getElementById' of undefined
当我尝试访问 iFrame 文本框时。
EDIT2:问了一个新问题,因为它们不相关。
最佳答案
只要您可以访问这两个域,此解决方案甚至可以跨域使用。有很多边缘情况,但至少你可以从这个开始。您还可以添加计时器事件以确保 iFrame 的大小始终正确,这样您就永远不会有滚动条。请记住,由于使用了 postMessage,这仅适用于支持 HTML5 的浏览器。
在 iFrame 中
function resize(){
var body = document.body,
html = document.documentElement,
height = body.offsetHeight;
if(height === 0){
height = html.offsetHeight;
}
parent.postMessage({'action':'RESIZE', 'height':height}, '*');
}
parent
function handleMessage(e) {
if (e.data.action == 'RESIZE') {
var targetHeight = e.data.height;
$('#iFrame').height(targetHeight);
}
}
window.addEventListener("message", handleMessage, false);
关于javascript - 如何动态调整 iFrame 的大小(跨浏览器解决方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13135019/