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是不能跨域的,如果跨域则无法进行操作。

  • 相关阅读:
    日报10.29
    日报10.28
    日报10.27
    周进度总结-6
    日报10.25
    日报10.23
    日报10.22
    日报10.21
    日报10.18
    STL bitset
  • 原文地址:https://www.cnblogs.com/kongxs/p/3985967.html
Copyright © 2011-2022 走看看