开发者

make iframe height fit content

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 t开发者_Python百科o 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.


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

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

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

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

document.getElementById("divId").offsetHeight;

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

jquery:

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

regular js:

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


<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

window.parent.window.onContentChange()


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

<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>


Here's a solution using jQuery:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜