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

  • 相关阅读:
    MacOS Catalina 10.15安装教程,启动U盘制作及安装方法
    苹果macOS Catalina 10.15 正式版推送了,要不要升级,需要注意什么?
    Sublime Text Mac如何进行按键绑定?
    Mac软件应用程序打开出现意外退出、崩溃解决办法
    使用VScode Mac版编译配置C/C++程序完整图文教程
    pycharm pro 2019 mac重构技巧?
    一体化数据库管理Navicat Premium for Mac的命令提示代码
    jsonp理解
    linux系统命令大全
    java学习笔记之分层增删改查
  • 原文地址:https://www.cnblogs.com/kongxs/p/3985967.html
Copyright © 2011-2022 走看看