【发布时间】:2016-06-16 19:37:06
【问题描述】:
我一直在寻找一种根据 iframe 内的内容自动调整高度的解决方案,这似乎适用于 chrome。
但由于某种原因,如果我等待网站完全加载,然后单击主页上的“Wall”标签,则 iframe 内容不可见,因为高度为设置为“4px”。
同样,如果您在加载时或加载之前点击墙标签,它会完全正常工作。
我猜这与来源有关。 我遇到问题的网站在这里:http://xefrontier.com/
谁能告诉我为什么会出现这种现象?
这是来源:
function resizeIframe(obj){
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
function getDocHeight(doc) {
doc = doc || document;
// stackoverflow.com/questions/1145850/
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function setIframeHeight(id) {
var iframe_board = document.getElementById(id);
var doc = iframe_board.contentDocument? iframe_board.contentDocument:
iframe_board.contentWindow.document;
iframe_board.style.visibility = 'hidden';
iframe_board.style.height = "10px"; // reset to minimal height ...
// IE opt. for bing/msn needs a bit added or scrollbar appears
iframe_board.style.height = getDocHeight( doc ) + 4 + "px";
iframe_board.style.visibility = 'visible';
}
document.getElementById('iframe_board').onload = function() { // Adjust the Id accordingly
setIframeHeight(this.id);
}
【问题讨论】:
-
嗨@MarkKang 确保包含iframe 的容器具有
overflow-x:hidden和overflow-y: auto or scroll我提供的demo 我提供的您已使用Firefox PC 进行了测试您使用的是Mac 吗?顺便说一句,如果为docHeight(x)正确设置了参数,那么 4 应该以数字形式相加,而不是 concat。 -
嘿@zer00ne 我还没有完全尝试过你的编码,但我想我会试一试。是的,我是 Mac 用户。
-
我知道,好吧,而是在 iframe 加载事件上调用函数`resizeIframe`,稍后在
window.onload = resizeIframe;处触发,不要在表达式末尾添加“`()'”。把它放在脚本标签的最后。 -
我猜它正在工作!谢谢。
-
欢迎您,先生。我应该回答,因为我花了好几天才弄清楚。
标签: javascript jquery iframe