Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

javascript - Resize iframe to content with Jquery

I'm trying to resize an iframe dynamicly to fit its content. To do so I have a piece of code:

$("#IframeId").height($("#IframeId").contents().find("html").height());?

It doesnt work. Is it because of cross-domain issue? How do I get it to fit? Please take a look at Fiddle: JsFiddle

ps I have set the html and body of the link height:100%;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to apply your code on the iframe load event, so the height is already known at that time, code follows:

$("#IframeId").load(function() {
    $(this).height( $(this).contents().find("body").height() );
});

See working demo . This demo works on jsfiddle as I've set the iframe url to a url in the same domain as the jsfiddle result iframe, that is, the fiddle.jshell.net domain.

UPDATE:
@Youss: It seems your page for a strange reason don't get the body height right, so try using the height of the main elements instead, like this:

$(document).ready(function() {
    $("#IframeId").load(function() {
            var h = $(this).contents().find("ul.jq-text").height();
            h += $(this).contents().find("#form1").height();
            $(this).height( h );
        });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...