javascript - 如何使用 jQuery 从父页面引用 <iframe> 的文档对象?

标签 javascript jquery iframe document parent

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

具体来说,我试图在内容呈现(加载)后找到 <iframe>d 文档的高度,这样我就可以从父页面调整 <iframe> 的大小以匹配 <iframe> 的高度> 的内容完全一样。

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

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

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

出于某种原因,我发现了很多从 <iframe> 中访问父文档对象的方法(大多数使用纯 JavaScript),但反过来却不行。

在此先感谢您的帮助!

最佳答案

您是否也等待 iframe 加载?

无论如何,以下代码在 FF3.5、Chrome 3、IE6、IE7、IE8 中都有效。
托管演示:http://jsbin.com/amequ (可通过 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>

关于javascript - 如何使用 jQuery 从父页面引用 &lt;iframe&gt; 的文档对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573220/

相关文章:

javascript - Bootstrap 中文本和图像的列未对齐

javascript - 如何从 iframe 中设置 Chrome 打印对话框的默认文件名?

javascript - 当 iframe 内容更改时调整 iframe 高度(同一域)

javascript - 使用 gulp-watch 忽略隐藏文件

javascript - 如何从当前导航器系列的 Highcharts 中获取摘要?

jquery autoResize 破坏了文本区域的表单验证

css - 在不创建额外空白的情况下在 iFrame 中缩小文本/内容

javascript - 如何 grep JavaScript 或 jQuery 中包含的 JSON 数组

javascript - "const"与 "console.log"一起使用时 undefined variable

javascript - 通过标签 html 中的照片列表进行更改