zoukankan      html  css  js  c++  java
  • js操作iframe总结

      一 在父页面操作子页面    

     
    IE下操作IFrame内容的代码:
       
    document.frames["MyIFrame"].document.getElementById("s").style.color="blue";
    但是这在Firefox下无效。
    所以,想到在Firefox下用FireBug来调试。经过调试发现在Firefox下可用以下代码来实现:
     
    document.getElementById("MyIFrame").contentDocument.getElementById("s").style.color="blue";

     详细代码如下:
    TestIFrame.htm:
    <html>
    <head>
    <script type="text/javascript">
    function f(){
            var doc;
    
            if (document.all){//IE
                    doc = document.frames["MyIFrame"].document;
            }else{//Firefox    
                    doc = document.getElementById("MyIFrame").contentDocument;
            }
    
            doc.getElementById("s").style.color="blue";
    }
    </script>
    </head>
    <body onload="f()">
    
    <iframe id = "MyIFrame" name = "MyIFrame" src = "MyIFrame.htm" width = "100" height="100"></iframe>
    
    </body>
    </html>

    其实可以用一种通用方法:

    <html>
    <head>
    <script type="text/javascript">
    function f(){
            //var doc = window.frames["MyIFrame"].document;  2中都可以
            var doc = document.getElementById("MyIFrame").contentDocument;
            doc.getElementById("s").style.color="blue";
    }
    </script>
    </head>
    <body onload="f()">
    
    <iframe id = "MyIFrame" name = "MyIFrame" src = "MyIFrame.html" width = "100" height="100"></iframe>
    
    </body>
    </html>

       二 在子页面中操作父页面     

      父页面操作子页面

    <html>
    <head>
    </head>
    <body>
    
            <h2 id="s">55555555555555555555555555</h2>
            <script>
           //window.parent是获得父窗口的window对象
    window.parent.document.getElementById("txt").innerHTML="你猜怎么样"; </script> </body> </html>

       三 在父页面调用子页面的函数  

    <html>
    <head>
    
    </head>
    <body>
    <iframe id = "MyIFrame" name = "MyIFrame" src = "MyIFrame.html" width = "100" height="100"></iframe>
    <script type="text/javascript">
        window.onload=function(){
            //window.frames["MyIFrame"].window.test();
            document.getElementById("MyIFrame").contentWindow.test(); 
        }
    </script>
    </body>
    </html>

      四  在子页面调用父页面的函数  

    <html>
    <head>
    </head>
    <body>
            <h2 id="s">55555555555555555555555555</h2>
              <script type="text/javascript">
                    window.onload=function(){
                    window.parent.test(); 
                }
            </script>
    </body>
    </html>

    总结:iframe中的src是不能跨域的,如果跨域则无法进行操作。

  • 相关阅读:
    HDU 5514 Frogs 欧拉函数
    HDU 5521 Meeting 最短路
    HDU 5527 Too Rich 贪心
    HDU 5525 Product 数论
    MFC中 编辑框内组合键的使用
    MyEclipse+Struts+Hibernate+Mysql开发环境配置
    SSH框架介绍
    mysql忘记密码的解决办法
    VS2010 MFC中 窗口分割的实现
    VS2010 MFC中 创建文件夹及文件判空的方法
  • 原文地址:https://www.cnblogs.com/kongxs/p/3985967.html
Copyright © 2011-2022 走看看