html iframe 的使用方法


如何调用 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)
}

150

声明:Web前端小站 - 前端博客 - 王搏的个人博客|版权所有,违者必究|如未注明,均为原创

转载:转载请注明原文链接 - html iframe 的使用方法

评论
孙瑞杰生日