由於瀏覽器安全原因以下contentWindow 對象必須起一個頁面服務才能使用(通過域名或ip地址來訪問)並且的保證父頁面與子頁面是在同一域名下,不然是會報錯的
父頁面調用子頁面
獲取父頁面的ifram的id或calss之后可以通過contentWindow這個對象獲取子頁面的元素和方法.父頁面調用子頁面的元素和方法時,必須要等iframe加載完畢,或者在onload 方法里執行,不然是獲取不到的!
contentWindow 可取得子窗口的 window 對象。
document.getElementById('main').contentWindow.document.querySelector(".warp");//獲取父頁面的方法
document.getElementById('main').contentWindow.childFn();//獲取子頁面的方法並執行
子頁面調用父頁面
在子頁面通過window.parent.fn()可以獲取並執行父頁面的方法
window.parent.parentFn()
實例:
父頁面
<iframe scrolling="no" id="main" name="main" frameborder="0" src="iframe子頁面1.html"></iframe> <script type="text/javascript"> //根據ID獲取iframe對象 var ifr = document.getElementById('main'); ifr.onload = function() { /*獲取子頁面的dom元素*/ var warp=ifr.contentWindow.document.querySelector(".warp"); //獲取子頁面的元素 console.log(warp); ifr.contentWindow.childFn() //調用子頁面的方法 } function parentFn(){ alert("我是父頁面的方法") } </script>
子頁面
<p onclick="parentFn">購物車</p> <script> var box=document.querySelector("p"); box.onclick=function(){ window.parent.parentFn()//點擊時調用父頁面的方法 } function childFn(){ console.log("我是子頁面的方法") } </script>