zoukankan      html  css  js  c++  java
  • [JavaScript]JavaScript处理iframe的动作

    随着W3C一声令下,几年前使用非常频繁的frameset + frame已完成使命,光荣退伍。作为frameset的替代方案(姑且这么称吧),iframe的使用也多了起来。较frameset方案,iframe在使用上更加灵活,文档结构更加友好。

    本文就js操作iframe在不同浏览器(没错,又是浏览器兼容…)的差异性做一些说明,力求总结出一个适应于所有主流浏览器的方案,笔者只测试了IE 6/7/8(以下简称IE)和FireFox 5.0(以下简称FF)。

    约定与定义

    iframeElement:指的是iframe的DOM元素表示,即用document.getElemenetById()等方法获取的DOM对象 iframeId: 指iframe的属性id,如<iframe id=”someid”> iframeName:指iframe的属性name,如<iframe name=”somename”> iframeIndex:从0开始编号的iframe索引,若页面中有N个frame,则其值范围为0 – n-1 iframeWindow:指的是iframe的window对象 标准浏览器:符合W3C标准的浏览器的统称,如FireFox

    一、 在父页面中获取iframe的window对象

    获得了window对象后,就可以调用iframe页面中定义的方法等。

    IE:可以通过iframeId、window.iframeId、window.iframeName、 window.frames[iframeId]、window.frames[iframeName]、 window.frames[iframeIndex]和iframeElement.contentWindow这6种方法来获取iframe的 window对象。

    FF:可以通过window.iframeName、window.frames[iframeName]和iframeElement.contentWindow这3种方法获取window对象。

    总结:为了兼容大多数浏览器,应使用iframeElement.contentWindow来获取。见如下代码:

    1. <iframe id="iframe1" name=”iframe1” src="frame1.html"></iframe
    2. <script type="text/javascript"
    3.     //获取iframe的window对象 
    4.     var iframe = document.getElementById('iframe1').contentWindow; 
    5. </script

    二、 在父页面中获取iframe的document对象

    标准浏览器可以通过iframeElement.contentDocument来引用iframe的doument对象,但是IE浏览器(又是这斯…)不支持,确切说应该是IE 6/7,笔者发现在IE8中已经可以用此方法来获取了。

    当然,因为document是window的一个子对象,你也可以先获取iframe的window对象,再通过window.document来引用。

    总结:应使用以下两方法来获取,见代码:

    1. <iframe id="iframe1" src="frame1.html"></iframe
    2.  
    3. <script type="text/javascript"
    4.     //获取iframe的document对象        
    5.     //方法1 
    6.     var iframe = document.getElementById('iframe1').contentWindow.document; 
    7.  
    8.     //方法2 
    9.     function getIframeDom(iframeId) { 
    10.         return document.getElementById(iframeId).contentDocument || window.frames[iframeId].document; 
    11.     } 
    12. </script

    三、 iframe页面获取父页面的window对象

    parent:父页面window对象

    top:顶层页面window对象

    self:始终指向当前页面的window对象(与window等价)

    适用于所有浏览器,当拿到了父页面的window对象后,就可以访问父页面定义的全局变量和函数,这在iframe交互里经常用到。

  • 相关阅读:
    Python学习札记(十五) 高级特性1 切片
    LeetCode Longest Substring Without Repeating Characters
    Python学习札记(十四) Function4 递归函数 & Hanoi Tower
    single number和变体
    tusen 刷题
    实验室网站
    leetcode 76. Minimum Window Substring
    leetcode 4. Median of Two Sorted Arrays
    leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions 、434. Number of Islands II(lintcode) 并查集 、178. Graph Valid Tree(lintcode)
    刷题注意事项
  • 原文地址:https://www.cnblogs.com/myblogslh/p/4922197.html
Copyright © 2011-2022 走看看