我想根据 iframe 内容的变化来更改 iframe 高度,但如果 iframe 内容的高度值低于 150px,我就会遇到问题。
我已经在 Firefox 和 Chrome 中测试了这段代码,结果相同。 这里可以测试一下https://jsfiddle.net/bqvc0pp5/17/
据我所知,如果未指定高度,iframe 将自动具有 150 像素(无边框)。 在这个例子中,我将值增加到 300px 然后降低到 200px 而不是 50px 。在将 50px 转换为 150px 之前一切正常;
var iframe = document.createElement('iframe');
iframe.setAttribute("scrolling","no");
iframe.onload = () => {
builtElement();
};
//append iframe to main document
document.body.appendChild(iframe);
var k=0;
function builtElement(){
var div = document.createElement('div');
div.style.height="50px";
div.style.backgroundColor="salmon";
iframe.contentWindow.document.body.style.margin="0px";
iframe.contentWindow.document.body.appendChild(div);
div.addEventListener("click", () =>{
if(k==0){
div.style.height="300px";
}
if(k==1){
div.style.height="200px";
}
if(k==2){
div.style.height="50px";
}
if(k>=2) k=0;
else k++;
updateIframeHeight();
});
}
function updateIframeHeight(){
//I need to reset height or else scrollHeight will be the last max value
iframe.style.height="";
var height = iframe.contentWindow.document.body.scrollHeight;
//this is a dirty hack where I can check if offsetHeight is lower than 150px
var offsetHeight = iframe.contentWindow.document.body.offsetHeight;
//if(offsetHeight<150) height=offsetHeight;
console.log("scrollHeight: "+height);
console.log("scrollHeight: "+offsetHeight);
iframe.style.height=height+"px";
}
如果我做一些修改并检查 offsetHeight
是否低于 150px,它就可以工作。
var offsetHeight = iframe.contentWindow.document.body.offsetHeight;
if(offsetHeight<150) height=offsetHeight;
这是最好的方法吗?
更新:在一个真实的例子中,iframe body 包含多个元素,但只有某些元素改变了高度,从而改变了 body 的 scrollHeight
最佳答案
我找到了解决方案。您所要做的就是将大小设置为 0px;
iframe.style.height="0px";
我之前所做的 iframe.style.height="";
默认将高度设置为 150px。看起来如果没有指定大小,iframe 大小将是 150px;
关于javascript - 值低于 150px 的 iframe 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38730034/