使用 javascript/html 控制 iframe 内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19498725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Control iframe content with javascript/html
提问by Ilan Kleiman
Within my webpage I have an iframe like so:
在我的网页中,我有一个像这样的 iframe:
<iframe src="thispage.html" width="100%" height="600" frameBorder="2"></iframe>
(The iframe is of a page on the same site...)
(iframe 是同一站点上的一个页面...)
My question is, is it possible to use javascript on the page that has the iframe to control the 'thispage.html' (like use javascript functions?)
我的问题是,是否可以在具有 iframe 的页面上使用 javascript 来控制“thispage.html”(例如使用 javascript 函数?)
回答by Kaf
Yes you can. Say your iframe
's ID is 'myIFrame'
是的你可以。假设你iframe
的 ID 是'myIFrame'
<iframe id="myIFrame" src="thispage.html"
width="100%" height="600"
frameBorder="2">
</iframe>
Then, add the following in your JavaScript:
然后,在您的 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();
Hope it helps :)
希望能帮助到你 :)
回答by Yuriy Galanter
Yes, if you give your iframe an ID, for example
是的,如果你给你的 iframe 一个 ID,例如
<iframe src="thispage.html" width="100%" height="600" frameBorder="2" id="MyIframe"></iframe>
You can access the inner window like this:
您可以像这样访问内部窗口:
var iw = document.getElementById("MyIframe").contentWindow;
So you can call its functions e.g.
所以你可以调用它的函数,例如
iw.theFunctionInsideIframe();
And you can locate the DOM elements like
你可以找到像这样的 DOM 元素
var anElement = iw.document.getElmentByID("myDiv");