如何从 iframe 元素更改元素属性

How to change elements attribute from iframe element?

本文关键字:元素 属性 iframe      更新时间:2023-09-26

我正在尝试从iframe内部设置div的高度。

我有类似的东西

<div id='test' style='height:150px;'>some stuff..</div>
<iframe id="test" src="http://www.myproject.com frameborder="0" scrolling="no">
   <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
   <title>test project</title>
   <link rel="stylesheet" type="text/css" href="g_reset.css">
   <script type="text/javascript" src="options.js"></script>
   </head>
   bunch of html...
   <a id='click' href='#'>click<a/>
</iframe>

我希望能够在单击iframe内的"单击"时更改"测试"div高度。

在我的options.js我有..

$('#click).click(function(){
   alert('pop')
   $('#test').attr('height','500');
})

警报会弹出,但它似乎不会改变div的高度。谁能帮我解决这个问题?多谢!

作为jQuery解决方案,你可以在iframe中使用这样的东西。

$('#test', window.parent.document).css('height', '500px');

$(window.parent.document).find('#test').css('height', '500px');

对于第一个示例,$()中的第二个参数是要在其中搜索的上下文。另请注意,我使用了css()而不是attr(),因为您正在尝试修改元素的样式,而不是属性。

试试这个:D

<a id='click' href='#' onClick='parent.document.getElementById('"test'").style.height='"50px'"'>click<a/>