如何引用< iframe>的文档对象?从父页面,使用jQuery? [英] How do I refer to the document object of an <iframe> from the parent page, using jQuery?

查看:158
本文介绍了如何引用< iframe>的文档对象?从父页面,使用jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问位于< iframe>中的网页的文档对象来自主页。换句话说,我有一个页面,其中包含< iframe>在其中,我想在该页面(父页面)上使用jQuery来访问该< iframe>的文档对象。

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

具体来说,我正在尝试在呈现其内容(onload)后找到< iframe> d文档的高度,以便我可以调整< iframe>的大小。来自父页面以准确匹配< 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.

如果重要,则此< iframe>是使用JavaScript在主机页面上创建的,并且与父页面位于同一个域中。我已经使用过这种类型的代码:

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>');

填充< iframe>有内容,但我不知道获取< iframe>的文档对象的确切语法。

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

出于某种原因,我找到了很多方法从< iframe>中访问父文档对象(大多数使用纯JavaScript),但不是相反。

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.

提前感谢您的帮助!

推荐答案

您是否等待加载iframe?

Did you wait for the iframe to load as well?

无论如何,以下代码适用于FF3.5,Chrome 3 ,IE6,IE7,IE8。

托管演示: http://jsbin.com/amequ(可通过 http://jsbin.com/amequ/edit 编辑)

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>

这篇关于如何引用&lt; iframe&gt;的文档对象?从父页面,使用jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆