如何调用 iframe 里的方法,获取 iframe 里的document。
1、iframe 的 onload 事件
首先获取iframe document;
let iframe = document.getElementById(“iframe”);
iframe.onload = function() {
// 在这执行需要的代码
}
注意:只可惜它在IE下经常无效,因为在IE下它最多只能被激活一次,而且无论你有多少个iframe,被激活的也只能是最后一个的。
2、调用 iframe 内部网站的方法,以及获取 iframe 的document
需要在onload里进行,因为 iframe 需要先加载成功。
let iframe = document.getElementById(“iframe”);
iframe.onload = function() {
const iwindow = iframe.contentWindow // 获取iframe的window对象
// 比如iframe里有个test的方法,可以直接调用。
iwindow.test();
const idoc = iwindow.document // 获取iframe的document
// 获取到dom后可以操作,比如我们这里来改变一个字体的颜色
let title_dom = idoc.getElementsByClassName('title')[0]
title_dom.style.color = '#FFF'
// 也可以给iframe创建style
// 先获取iframe的html元素
let box = idoc.getElementsByTagName('html')[0];
let style = document.createElement('style');
style.innerHTML = `
.title {
color: red;
}
`
box.appendChild(style)
}