【问题标题】:Control iframe content with javascript/html使用 javascript/html 控制 iframe 内容
【发布时间】:2013-10-21 15:31:19
【问题描述】:

在我的网页中,我有一个像这样的 iframe:

<iframe src="thispage.html" width="100%" height="600" frameBorder="2"></iframe>

(iframe 是同一站点上的页面...)

我的问题是,是否可以在具有 iframe 的页面上使用 javascript 来控制“thispage.html”(比如使用 javascript 函数?)

【问题讨论】:

  • thispage.html 是主 html 文件或您正在加载到 iframe 中的文件。

标签: javascript html


【解决方案1】:

是的,你可以。假设您的 iframe 的 ID 是 'myIFrame'

<iframe id="myIFrame" src="thispage.html"
    width="100%" height="600"
    frameBorder="2">
</iframe>

然后,在您的 JavaScript 中添加以下内容:

// Get the iframe
const iFrame = document.getElementById('myIFrame');

// Let's say that you want to access a button with the ID `'myButton'`,
// you can access via the following code:
const buttonInIFrame = iFrame.contentWindow.document.getElementById('myButton');

// If you need to call a function in the iframe, you can call it as follows:
iFrame.contentWindow.yourFunction();

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    是的,如果你给你的 iframe 一个 ID,例如

    <iframe src="thispage.html" width="100%" height="600" frameBorder="2" id="MyIframe"></iframe>
    

    您可以像这样访问内部窗口:

    var iw = document.getElementById("MyIframe").contentWindow;
    

    所以你可以调用它的函数,例如

    iw.theFunctionInsideIframe();
    

    你可以定位 DOM 元素,比如

    var anElement = iw.document.getElmentByID("myDiv");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2010-09-13
      • 2017-03-30
      • 2012-02-07
      • 2017-03-12
      • 2012-05-28
      相关资源
      最近更新 更多