How to change height of iframe based on dynamic conent within the iframe?

最后都变了- 提交于 2019-12-03 08:46:23

问题


I have an iframe that has dynamic content. If the answers specific questions, additional information displays (hidden div becomes visible). I'd like the height of the iframe to expand. I know this question has been asked on here multiple times, but it seems like it is typically when a different page within the iframe is loaded, not when content is changed dynamically within the iframe.

Here is an example I tried to put together using jsFiddle:

iframe: http://jsfiddle.net/B4AKc/2/

page: http://jsfiddle.net/PmBrd/

Any ideas?


回答1:


Does this work for you?

http://jsfiddle.net/PmBrd/1/

Code:

var iframe = document.getElementById("ifr").contentWindow;

iframe.$(".toggle_div").bind("change", function () {
    $("#ifr").css({
        height: iframe.$("body").outerHeight()
    });
});

Since you mentioned they are in the same domain, it's just a matter of doing something similar with your real app.




回答2:


Check this one. You can get the iframe size using javascript itself.
Using setInterval, check the window height each time.

< iframe src='<YOUR_URL>' frameborder='0' scrolling='no' id='frame_id' style='overflow:hidden; width:984px;' >
</iframe>

<script language="javascript" type="text/javascript">
setInterval(function(){
    document.getElementById("frame_id").style.height = document.getElementById("frmid").contentWindow.document.body.scrollHeight + 'px';
},1000)
</script>

Check this




回答3:


Esailija's answer works fine, but this is nicer imo.

$('#ifr').contents($(".toggle_div")).bind("change", function () {
    $("#ifr").height($("#ifr").contents().find("html").height());
});



回答4:


may be a bit late, as all the other answers are from 2011 :-) but... here´s my solution. Tested in actual FF, Chrome and Safari 5.0

$(document).ready(function(){
    $("iframe").load( function () {
        var c = (this.contentWindow || this.contentDocument);
        if (c.document) d = c.document;
        var ih = $(d).outerHeight();
        var iw = $(d).outerWidth();
        $(this).css({
            height: ih,
            width: iw
        });
    });
});

Hope this will help anybody.




回答5:


Take a look at the jQuery postMessage plugin. It allows you to pass information from the child frame to the parent. You could change the code inside the child frame to post the content height to the parent on content change, which the parent could then use to resize the iframe accordingly.

The two pages must be on the same domain to work.

I hope this helps!



来源:https://stackoverflow.com/questions/8279489/how-to-change-height-of-iframe-based-on-dynamic-conent-within-the-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!