让前端飞Web前端之路前端开发

iframe父子相互调用,相互操作DOM

2019-06-14  本文已影响3人  李佳明先生

一、相互调用方法

子级页面调用父级页面的方法:

window.parent.parentFunction();

parentFunction为父级页面的自定义函数

父级页面调用子级页面的方法:

document.getElementById("iframeID").contentWindow.childFunction();

iframeID为目标iframe的id,childFunction为子级页面的自定义函数

二、相互操作dom

子级页面操作父级页面dom:

window.parent.document.getElementById("parentID").style.color='yellow';

父级页面操作子级页面dom:

document.getElementById('iframeID').contentDocument.getElementById('childID').style.color='red'

iframeID为目标iframe的id,childID为子级页面的dom的id

注意:只有当iframe加载完之后才可以父级操作子级dom,否则会报错,可以尝试window.onload来解决此问题。

上一篇 下一篇

猜你喜欢

热点阅读