iframe现在已经用得比较少了,但是并不是所有的都没有用,这里记录下iframe的使用
父操作子
直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| //父页面 <!doctype html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <input type="button" value="改变" id="input1"> <iframe src="iframe1.html" id="iframe1"></iframe> <iframe src="iframe2.html" id="iframe2"></iframe> <div id="div1">parent</div> <input type="button" value="change1" id="change1"> <input type="button" value="change2" id="change2"> <iframe src="iframe1.html" id="iframe3" scrolling="no"></iframe> </body> <script> //chorme测试需要服务器环境
//父操作子
var oInput = document.getElementById("input1"); var oIframe = document.getElementById("iframe1"); oInput.onclick = function(){ console.log(oIframe.contentWindow); // 获取到的是iframe的window对象,有了window对象,我们就可以做很多事情了...
//操作iframe中的元素 支持IE6,7 contentWindow oIframe.contentWindow.document.getElementById("div1").style.color = "red";
//获取iframe的document IE6,7不支持 oIframe.contentDocument.getElementById('div1').style.fontSize = "80px"; }
//iframe的onload事件,IE下的iframe的onload事件只能用绑定的形式 //创建一个iframe元素 var cIframe = document.createElement('iframe'); cIframe.src = 'iframe1.html'; document.body.appendChild(cIframe); oIframe.onload = function(){ alert(123); }
//IE绑定形式 // oIframe.attachEvent('onload',function(){ // alert(456); // })
//改变iframe的大小 var oInput1 = document.getElementById("change1"); var oInput2 = document.getElementById("change2"); var oIframe3 = document.getElementById("iframe3"); oIframe3.onload = function(){ function changeHeight(){ oIframe3.height = oIframe3.contentWindow.document.body.offsetHeight; } changeHeight() }
</script> </html>
|
子操作父
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <!doctype html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="div1" style="height:300px; width:300px; background:yellow">iframe1</div> <input type="button" value="改变" id="input1"> </body> <script> //子操作父 var oInput = document.getElementById('input1'); oInput.onclick = function(){ //获取父层的页面 window.parent window.parent.document.getElementById('div1').style.color = 'blue'; window.parent.document.getElementById('div1').style.fontSize = '80px';
//获取最顶层,多层嵌套的情况下使用 window.top window.top.document.getElementById('div1').style.color='red'; }
</script> </html>
|