JS操作网页中的iframe

 1 /*
 2 *parent.html
 3 */
 4 
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 6 <html xmlns="http://www.w3.org/1999/xhtml">
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 9 <title>这里是parent页面</title>
10 <script type="text/javascript">
11 window.onload = function (){
12     var oTxt = document.getElementById("txt");
13     var oBtn = document.getElementById("btn");
14     var oI = document.getElementsByTagName("iframe")[0];
15     console.log(oI);
16     var oW = oI.contentWindow;                        //获取iframe的Window对象
17     console.log(oW);
18     //debugger;                                                    //这个还不太会用
19     var oW2 = oI.contentWindow.document;        //获取iframe的document对象
20     console.log(oW2);
21     var oDiv = oW.document.getElementById("div1");
22     oBtn.onclick = function (){
23         if(oTxt.value==""){
24             oDiv.innerHTML = oDiv.innerHTML + "<hr>null<br><br>";
25         }else{
26             oDiv.innerHTML = oTxt.value + "<br><br><br><br>";
27         }
28     }
29 }
30 </script>
31 </head>
32 
33 <body>
34 
35 <input type="text" name="txt" id="txt" /> <input type="button" value="确定" id="btn" />
36 46541561456
37 
38 <br /><hr />
39 
40 <iframe src="son.html" frameborder="01" height="270" width="980"></iframe>
41 
42 <br /><br /><br /><br /><br />
43 
44 
45 45455
46 
47 </body>
48 </html>

 1 /*
 2 *son.html
 3 */
 4 
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 6 <html xmlns="http://www.w3.org/1999/xhtml">
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 9 <title>这里是iframe页面</title>
10 </head>
11 
12 <body>
13 
14 <h1>这里是Iframe的东西</h1>
15 <div id="div1">789404123<br />f4<br />fff<br /><br /></div>
16 
17 145620...0
18 
19 
20 
21 </body>
22 </html>
  • 在本地会产生跨域问题
  • 解决办法:放在自己安装的环境里运行或跑在服务器上
posted @ 2014-03-24 15:36  半颠者  阅读(337)  评论(0编辑  收藏  举报