使用javascript/html控制iframe内容

Ila*_*man 8 html javascript

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

<iframe src="thispage.html" width="100%" height="600" frameBorder="2"></iframe>
Run Code Online (Sandbox Code Playgroud)

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

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

Kaf*_*Kaf 12

是的你可以.假设您的iframeId是myIframe;

<iframe id="myIframe" 
        src="thispage.html" width="100%" height="600" frameBorder="2"></iframe>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

//get the iframe
var iframe = document.getElementById("myIframe");

//For ex; say you have a button called mybutton in thispage.html page
//you can access it as follows.
var btn = iframe.contentWindow.document.getElementById('mybutton');

//if you need to call a function
iframe.contentWindow.yourFunction();
Run Code Online (Sandbox Code Playgroud)