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
371 views
in Technique[技术] by (71.8m points)

javascript - How do I refer to the document object of an <iframe> from the parent page, using jQuery?

I'm trying to access the document object of a page that lives in an <iframe> from the host page. In other words, I have a page that has an <iframe> in it, and I want to use jQuery on that page (the parent page) to access the document object of that <iframe>.

Specifically, I'm trying to find the height of the <iframe>d document once its content is rendered (onload) so that I can then resize the <iframe> from the parent page to match the height of the <iframe>'s content exactly.

If it's important, this <iframe> is created on the host page using JavaScript, and is in the same domain as the parent page. I already use this type of code:

$('iframe').contents().find('body').append('<p>content</p>');

to populate the <iframe> with content, but I don't know the exact syntax for getting the <iframe>'s document object.

For some reason I'm finding a lot of ways to access the parent's document object from within an <iframe> (most with plain JavaScript), but not the other way around.

Thanks in advance for any help!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Did you wait for the iframe to load as well?

Anyway, the following code works in FF3.5, Chrome 3, IE6, IE7, IE8.
Hosted Demo: http://jsbin.com/amequ (Editable via http://jsbin.com/amequ/edit)

<iframe src="blank.htm" ></iframe> 

<script> 
  var $iframe = $('iframe'); 

  /*** 
  In addition to waiting for the parent document to load 
  we must wait for the document inside the iframe to load as well. 
  ***/ 
  $iframe.load(function(){       
    var $iframeBody = $iframe.contents().find('body'); 

    alert($iframeBody.height()); 

    /*** 
    IE6 does not like it when you try an insert an element 
    that is not made in the target context. 
    Make sure we create the element with the context of 
    the iframe's document. 
    ***/ 
    var $newDiv = $('<div/>', $iframeBody.get(0).ownerDocument); 
    $newDiv.css('height', 2000); 

    $iframeBody.empty().append($newDiv); 

    alert($iframeBody.height()); 
  }); 
</script>

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

...