【发布时间】:2010-12-07 02:10:30
【问题描述】:
我正在尝试从主机页面访问位于
具体来说,我试图在
如果它很重要,则此
$('iframe').contents().find('body').append('<p>content</p>');
用内容填充
出于某种原因,我找到了很多从
提前感谢您的帮助!
【问题讨论】:
标签: javascript jquery iframe document parent
我正在尝试从主机页面访问位于
具体来说,我试图在
如果它很重要,则此
$('iframe').contents().find('body').append('<p>content</p>');
用内容填充
出于某种原因,我找到了很多从
提前感谢您的帮助!
【问题讨论】:
标签: javascript jquery iframe document parent
您是否也等待 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>
【讨论】:
如果您的 iframe 标签没有 src 属性或使用 javascript 或 jquery 动态创建,您可以使用此代码 sn-p 引用 iframe 的文档并使用 jquery 进行操作:
//in your html file
<iframe id="myframe"></iframe>
//your js
var doc = $ ( '#myframe' )[0].contentWindow.document ;
doc.open () ;
doc.write ( "<div id='init'></div>" ) ;
doc.close () ;
var $myFrameDocument = $ ( '#myframe' ).contents ().find ( '#init' ).parent () ;
现在您可以访问 dom 并将一些 html 添加到您的 iframe:
$myFrameDocument.html ( '<!doctype html><html><head></head><body></body></html>' );
【讨论】:
$('iframe').contents().get(0)
或
$('iframe').contents()[0]
将返回页面上第一个 iframe 的文档。记住 jQuery 对象是匹配的 DOM 元素的数组
【讨论】:
有很多方法可以访问 iframe:
例如,我们有这个 HTML 页面:
还有 JS:
frames[0] == frames['my_frame_name'] == document.getElementById('my_frame_id').contentWindow // true
【讨论】:
我在最近的一个项目中不得不这样做,我使用了这个:
<iframe src="http://domain.com" width="100%"
border="0" frameborder="0" id="newIframe"
onload="$(this).css({height:this.contentWindow ? this.contentWindow.document.body.scrollHeight + (20) : this.contentDocument.body.scrollHeight + (20)});"
style="border:none;overflow:hidden;">
</iframe>
虽然我有内联函数(在我的项目中很有意义,因为 iframe 是通过 PHP 生成的),但如果您通过 javascript 附加 iframe,它将类似于
$("#container").append('<iframe src="http://domain.com" width="100%" border="0" frameborder="0" id="newIframe" style="border:none;overflow:hidden;"></iframe>');
$("#newIframe").load(function(){
var _this=$("this")[0];
$(this).css({
height:
_this.contentWindow ? _this.contentWindow.document.body.scrollHeight + (20) : _this.contentDocument.body.scrollHeight + (20)});
});
//contentWindow.document.body is for IE
//contentDocument.body is for everything else
【讨论】: