Set iframe height to that of internal content (on same domain)
I have an iframe embedded within my page - it's just part of my page, not the whole thing. I am reloading the iframe dynamically and want it to resize according to the height of the content within it.
The content is on the same domain, so (hopefully?) no need for a solution as complex as that given in Resizing an iframe based on content.
This is the code I'm using to resize it, but it isn't working. The frame reloads OK, but the height always stays the same. Can anyone advise?
I've also tried the top solution in How to autosize an iframe without any luck.
I think it could be because the page inside the iframe takes a while to load, so it hasn't finished loading by the time the height is set. Maybe.
<iframe frameborder=0 border=0 src="" width="100%" height="400px" name="commentframe" id="commentframe"></iframe>
function reload_frame(uid) {
document.getElementById('commentframe').src = "comments.html?" + uid;
document.getElementById('commentframe').height = document.getElementById('commentframe').contentWindow.document.body.scrollHeight + "px";
}
Update:
Trying, with no luck:
<iframe frameborder=0 border=0 src="" width="100%" height="400px" name="commentframe" id="commentframe" onload="reload_frame()"></iframe>
function reload_frame() {
var commentframe = document.getElementById('commentframe');
commentframe.s开发者_开发问答tyle.height = (commentframe.scrollHeight + 10).toString() + "px";
}
It does resize the iframe, but only to +10px of its original height - if the content is longer than this, it is still hidden.
Maybe I need an onload event inside the body of the iframe itself?
<script type="text/javascript">
function ajustHeight() {
$("#myIframe").parent()[0].style.height = ($("#myIframe")[0].scrollHeight + 150).toString() + "px";
}
</script>
<iframe id="myIframe" src="mypage.html" width="100%" height="100%" onload="ajustHeight()"></iframe>
In modern browsers and with many doctypes, scrollHeight
will return the iframe height calculated by the browser and not the content height, so above snippets won't work in most cases.
You can set the iframe to the content height using the following snippet.
JS:
$('#ifm').load(function() {
$(this).height( $(this)[0].contentWindow.document.body.scrollHeight + 24);
});
HTML:
<iframe id="ifm src="..."></iframe>
Please note that this will work only if the iframe URL is on the exact same domain of the page containing the iframe itself.
without jquery:
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById("blogFrame");
iframe.parentNode.style.height = iframe.scrollHeight + "px";
}
</script>
精彩评论