在最近的项目里面,用到了不少关于iframe父子传参通信的相关操作,记录一下,虽然很简单,但是确实十分有用的;
iframe通信可以分为2种,跨域和非跨域两种.分别说明;
有一点很重要,iframe是可以给name 属性的;给上name 属性可以省下一些代码;
非跨域 父调子
//父页面<button class="b" id="b">点击</button><iframe src="a.html" name='child' id="f"></iframe><script> var ob=document.getElementById('b'); var msg='hellow,i'm your father!!' ob.onclick=function(){ if(child.document.readyState=="complete"){ child.window.fnChild(msg); //关键 } }</script>//子页面<script>function fnChild (arg) { console.log(arg); //确实得到了 hellow,i'm your father!!}</script>
父页面调用子页面使用 childFrameName.window.fnName();;当然有一点很重要,你需要判断iframe 里面的东西是否加载完成,如果加载未完成就调用的话是会报错的;
判断iframe 加载是否完成有2种方法
1,childFrameName.document.readyState=="complete"来判断;
2,childFrameName.onload=function(){} 使用onload 回调函数,把调用的方法都写在这个回调函数里面;
非跨域 子调父
//在父页面<div id="a" class="a"></div><iframe src="a.html" name='child' id="f"></iframe><script> function changeColor(){ var oDiv=document.getElementById('a'); oDiv.style.backgroundColor="red"; }</script>//在子页面<button class="ob" onclick="c()">anniu</button><script> function c(){ parent.window.changeColor(); //关键 }</script>
同样的,在子页面调用父页面的方法使用 parent.window.fnName()就可以了;
这种操作难免会遇到父页面获取子页面的元素,或者子页面获取父页面的元素进行操作;
非跨域 父页面获取子页面元素操作
首先,我们有几种方法拿到子页面的window对象或者doucument 对象,(还是使用上面的html)
//原生js 获取子页面window对象1, var childWindow=document.getElementById("f").contentWindow;2, var childWindow=document.getElementsByTagName('f')[0].contentWindow;//其实也就是普通的获取方法,只是后面多了一个contentWindow;//jqueryvar childWindow=$('#f').contentWindow;//获取子页面的document对象 (假设已经通过上面的方法得到了window对象)var frameDoc=childWindow.document;var frameBody=frameDoc.body;//jquery 也是跟上面的一样var frameDoc=$(childWindow.document);//原生获取元素childWindow.document.getElementById('a') //上面都已经拿到了子页面的window对象,所以获取子页面的元素也就只需要想普通操作那样获取就好childWindow.document.getElementById('a').style.color='red' //改个颜色//jq拿子页面元素$('#f').contents().find('#a'); //$('#f').contents 这相当于拿到了iframe 里面所有的dom;
新闻热点
疑难解答
图片精选