javascript 使 iframe 高度适合内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4940434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:25:28  来源:igfitidea点击:

make iframe height fit content

javascripthtmliframe

提问by Anonymous

How would I make an iframe's height adjust to the content within it? I assume you'd calculate the difference between the content height and iframe height (something I don't know how to do) and use that with a while loop to increment a variable to use as a height, but I can't wrap my head around how to actually do these things. Before asking: yes, the content in the frame is from my site. Not cross-domain.

我如何使 iframe 的高度适应其中的内容?我假设您会计算内容高度和 iframe 高度之间的差异(我不知道该怎么做)并将其与 while 循环一起使用来增加用作高度的变量,但我无法包装我的围绕如何实际做这些事情。在询问之前:是的,框架中的内容来自我的网站。不是跨域。

采纳答案by Valera

Not quite sure why you want to use an iframe and not a dynamic div filled, say, via ajax, but:

不太确定为什么要使用 iframe 而不是动态 div 填充,例如,通过 ajax,但是:

Put the content within the iframe into a div, then get the height of the div. I'd suggest using jquery like so:

将 iframe 内的内容放入一个 div 中,然后获取 div 的高度。我建议像这样使用 jquery:

$("#divId").height();

But if you can't use jquery, you should be able to use this:

但是如果你不能使用 jquery,你应该可以使用这个:

document.getElementById("divId").offsetHeight;

Then you'd need to set the iframe's height to whatever you got.

然后你需要将 iframe 的高度设置为你得到的任何值。

jquery:

查询:

$("#iframeId").height($("#divId").height());

regular js:

常规js:

document.getElementById("iframeId").style.height = 
document.getElementById("divId").offsetHeight;

回答by Itay Moav -Malimovka

<iframe id="moo" src="something.html"><iframe>
<script>
function onContentChange(){
  var NewSize=$('moo').getScrollSize();
  $('moo').setStyles({
    width: NewSize.x,
    height: NewSize.y
  });
}
</script>

and inside the somthing.html, on the bottom or onload event do something on the lines of

在 somthing.html 中,在底部或 onload 事件上做一些事情

window.parent.window.onContentChange()

回答by Luis

Render dynamically the iframe in javascript once the container element("td1") has been drawn.

一旦绘制了容器元素(“td1”),就在 javascript 中动态呈现 iframe。

<script type="text/javascript">
  var iframesrc = "@Href("~/about")";
  function init() {
  var vHeight = document.getElementById("td1").offsetHeight;
  document.getElementById("td1").innerHTML="<iframe style=\"width:100%; height:" + vHeight + "px\" src=\"" + iframesrc + "\"></iframe>";
  }
  window.onload = init; 
</script>

...

...

<td id="td1" style="width: 100%; height:100%;">                 
</td>

回答by Erik Bergstedt

Here's a solution using jQuery:

这是使用jQuery的解决方案:

$('#iframe').height($('#iframe').contents().find('body').height());