我正在尝试从主机页面访问位于 <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 从父页面引用 <iframe> 的文档对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573220/