iframe元素用法总结

url:http://www.cnblogs.com/rubylouvre/archive/2009/08/01/1536710.html

iframe是一个非常有用的标签,先不说早期用它来模型Ajax效果,现在富本文编辑器它也绝对是主角。但是它又是一个特别的元素,最早出现IE4.0中,后纷纷被其他游览器吸纳,由于IE不开源,iframe在各游览器中都有很大差异。首先我们看看它在各游览器中拥有什么属性——

火狐的iframe的所有属性:

scrollWidth, clientLeft, clientHeight, clientWidth, clientTop, getClientRects, getBoundingClientRect, getElementsByClassName, baseURI, textContent, compareDocumentPosition, getUserData, isSameNode, lookupNamespaceURI, setUserData, lookupPrefix, isDefaultNamespace, isEqualNode, dispatchEvent, removeEventListener, style,contentEditable, offsetParent, innerHTML, offsetLeft, offsetTop, offsetHeight, offsetWidth, contentWindow, src, contentDocument, className, id, title, tagName, removeAttributeNS, removeAttribute, getAttribute, getElementsByTagName, setAttribute, getElementsByTagNameNS, hasAttributeNS, setAttributeNS, hasAttribute, getAttributeNS, nextSibling, firstChild, prefix, nodeValue, childNodes, nodeName, namespaceURI, previousSibling, nodeType, localName, lastChild, ownerDocument, parentNode, attributes, appendChild, cloneNode, normalize, hasChildNodes, insertBefore, replaceChild, removeChild, hasAttributes, isSupported, getAttributeNode, setAttributeNode, removeAttributeNode, getAttributeNodeNS, setAttributeNodeNS, ELEMENT_NODE, ATTRIBUTE_NODE, TEXT_NODE, CDATA_SECTION_NODE, ENTITY_REFERENCE_NODE, ENTITY_NODE, PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, DOCUMENT_FRAGMENT_NODE, NOTATION_NODE, lang, dir, align, frameBorderheight, longDesc, marginHeight, marginWidth, name, scrolling,width , getSVGDocument, tabIndex, draggable, blur, focus, scrollIntoView, spellcheck, addEventListener, getFeature, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, scrollTop, scrollLeft, scrollHeight, firstElementChild, lastElementChild, previousElementSibling, nextElementSibling, childElementCount, children, querySelector, querySelectorAll

IE6的iframe所有属性

language, scrollHeight, isTextEdit, currentStyle,document , onmouseup, oncontextmenu, isMultiLine, clientHeight, onrowexit, onbeforepaste, onactivate, scrollLeft, lang, onmousemove, onmove, onselectstart, parentTextEdit, oncontrolselect, canHaveHTML, onkeypress, oncut, onrowenter, onmousedown, onpaste, className, id, onreadystatechange,onbeforedeactivate , hideFocus, dir, isContentEditable, onkeydown, clientWidth, onlosecapture, parentElement, ondrag, ondragstart, oncellchange, recordNumber, onfilterchange, onrowsinserted, ondatasetcomplete, onmousewheel, ondragenter, onblur, onresizeend, onerrorupdate, onbeforecopy, ondblclick, scopeName, onkeyup, onresizestart, onmouseover, onmouseleave, outerText, innerText, onmoveend, tagName, title, offsetWidth, onresize, contentEditable, runtimeStyle, filters, ondrop, onpage, onrowsdelete, tagUrn, offsetLeft, clientTop, style, onfocusout, clientLeft, ondatasetchanged, canHaveChildren, ondeactivate, isDisabled, onpropertychange, ondragover, onhelp, ondragend, onbeforeeditfocus, disabled, onfocus, behaviorUrns, accessKey, onscroll, onbeforeactivate, onbeforecut, readyState, all, sourceIndex, onclick, scrollTop, oncopy, onfocusin, tabIndex, onbeforeupdate, outerHTML, innerHTML, ondataavailable, offsetHeight, onmovestart, onmouseout, scrollWidth, offsetTop, onmouseenter, onlayoutcomplete, offsetParent, onafterupdate, ondragleave, children, parentNode, border, nodeValue, firstChild, name, align, marginWidth,contentWindow , hspace, frameSpacing, dataFormatAs, lastChild, ownerDocument, vspace, marginHeight, dataFld, attributes, dataSrc, src, frameBorder, nodeType, noResize, width, previousSibling, scrolling, nodeName, childNodes, longDesc, onload, nextSibling, heightallowTransparency

IE8的iframe所有属性

nextSibling, onresizeend, onrowenter, aria-haspopup, childNodes, ondragleave, canHaveHTML, onbeforepaste, ondragover, onbeforecopy, aria-disabled, onpage, recordNumber, previousSibling, nodeName, onbeforeactivate, accessKey, currentStyle, scrollLeft, onbeforeeditfocus, oncontrolselect, aria-hidden, onblur, hideFocus, clientHeight, styleonbeforedeactivate, dir, aria-expanded, onkeydown, nodeType, ondragstart, onscroll, onpropertychange, ondragenter, id, aria-level, onrowsinserted, scopeName, lang, onmouseup, aria-busy, oncontextmenu, language, scrollTop, offsetWidth, onbeforeupdate, onreadystatechange, onmouseenter, filters, onresize, isContentEditable, aria-checked, aria-readonly, oncopy, onselectstart, scrollHeight, onmove, ondragend, onrowexit, lastChild, aria-secret, onactivate, canHaveChildren, onfocus, onfocusin, isMultiLine, onmouseover, offsetTop, oncut, parentNode, tagName, className, onmousemove, title, role, behaviorUrns, onfocusout, onfilterchange, disabled, parentTextEdit, ownerDocument, offsetParent, aria-posinset, ondrop, ondblclick, onrowsdelete, tabIndex, onkeypress, aria-relevant, onlosecapture, innerText, aria-live, parentElement, ondeactivate, aria-labelledby, aria-pressed, children, ondatasetchanged, ondataavailable, aria-invalid, onafterupdate, nodeValue, onmousewheel, onkeyup, readyState, onmovestart, aria-valuenow, aria-selected, onmouseout, aria-owns, aria-valuemax, onmoveend, contentEditabledocument, firstChild, sourceIndex, outerText, isTextEdit, isDisabled, oncellchange, runtimeStyle, scrollWidth, aria-valuemin, onlayoutcomplete, onhelp, attributes, offsetHeight, onerrorupdate, onmousedown, clientTop, aria-setsize, clientWidth, onpaste, tagUrn, onmouseleave, onclick, outerHTML, ondrag, aria-controls, onresizestart, aria-flowto, ondatasetcomplete, aria-required, clientLeft, aria-describedby, all, onbeforecut, innerHTML, aria-activedescendant, aria-multiselectable, offsetLeft, frameSpacing, vspace, noResize, onload,height , marginHeight,border , longDesc, src, frameBorder, dataFormatAs,width , dataSrc, allowTransparency, contentDocument, name,contentWindow, marginWidth, dataFld, scrolling, align, hspace

通常要隐藏iframe的边框时需要用到frameborder属性,例如使用Dreamweaver可以生成如下代码:

   
<iframe frameborder=0 src='xxxx' width='xxx' height='xxx'></iframe>

但是如果使用DOM方式来生成一个iframe时IE却始终隐藏不了边框,例如:

   
var iframe = document.createElement('iframe');
iframe.setAttribute('frameborder',0);//Firefox下有效,IE下无效

我们需要直接对其属性进行赋值:

   
iframe.frameBorder=0;//Firefox和IE均有效

Internet Explorer 5.5 支持浮动框架的内容透明。如果想要为浮动框架定义透明内容,则必须满足下列条件:

  • 与 iframe 元素一起使用的 allowTransparency 标签属性必须设置为 true。(但设置了allowTransparency=true就遮不住select了!)
  • 在 iframe 内容源文档,background-color 或 body 元素的 bgColor 标签属性必须设置为 transparent。
具体事例

1. 包含框架页的代码。

   
<body bgColor="#eeeeee"> <iframe allowTransparency="true" src="transparent.htm"> </iframe>

2.transparent.htm页的代码。

   
<body bgColor="transparent">

对iframe进行操作:

   
var obj = document.getElementById(“iframe”);//获取对象
var dom = document.all.frames[“iframe”];//获取DOM

如果只想改变iframe的 src 或者 border ,scrolling 等attributes(与property不是一个概念,property是不能写在标签内的,比如:scrollHeight,innerHTML等),就需要用到第一种方法。

如果想取得iframe的页面(不是iframe本身)。就需要使用第二种方法,因为它取得的是一个完整的DOM模型,比如想得到iframe的document.body的内容,就只能用第二种方法

操作iframe中的DOM元素,需要注意以下两点:

  1. 必须先获取指定iframe的document
  2. 对于1,必须在页面load完以后才能获取;

控制Iframe中的页面的样式

   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title></title>
</head>
<body>
<iframe id="FF" src="B.htm"></iframe>
<input type="submit" value=" OK " onclick="OK()"/>
  
<script language="JavaScript">
function OK()
{
    // 操作iframe中内容的CSS
    var iframe = document.getElementById('FF');
    var body = iframe.contentWindow.document.body;
  
    body.style.marginTop = 50;
    body.style.padding = 0;
    body.style.fontSize = 30;
    body.style.textAlign = 'center';
    body.style.backgroundColor = 'red';
    body.style.color = 'blue';
}
</script>
</body>
</html>

去掉动态创建的iframe的边框

   
var iframe = document.createElement('iframe');
iframe.scrolling="no";//这两个属性的设置缺一不可。
iframe.frameborder="no";

window跟iframe标签是两回事 iframe的contentWindow属性是它里面的window

用getElementById才能取到iframe标签 ie直接用id得到的是里面的window

有关高度自适应问题

scrollHeight返回的是一个数字,没有带单位

在IE 下如果没有DTD声明,则按loose.dtd 解析,在设置对像的宽高时,会自动的加上单位"px"

将iframe的高度设为document.body的高度,也并不一定能成功,因为document.body的高度可能没有整个档的高度大,如使用了层

正确写法如下

var MainFrame = parent.document.getElementById("main");
MainFrame.style.height = document.documentElement.offsetHeight+"px";//最好在这上面还加上一个常数,如10

通过iframe访问主页面

注:伪Ajax效果就是这样模拟的了

   
 <script type="text/javascript">
       window.onload = function() {//这是主页面的代码
           var frame = document.getElementById("frame1");
           var msg = frame.contentDocument.getElementById("message");
           msg.innerHTML = "Hello World from Frame Page 1";
       };
   </script>
</pre>
<pre class="brush:javascript;gutter:false;toolbar:false"
//这是iframe部分!
 <div class="errordisplay" id="message">
original
</div>
  
<script type="text/javascript">
        var msg = window.parent.document.getElementById("message");
        msg.innerHTML = "Updated from iFrame";
</script>

document.getElementById取到的iframe是不能直接操作里面的document的,只能这样取:

  • 在IE为是frames[id].document或document.getElementById(id).contentWindow.document;
  • 在firefox为frames[name].contentDocument或document.getElementById(id).contentDocument;

最后切记iframe在FF中是不绑定任何事件的!例子参见的另一篇博文

setAttribute的”bug”已经Fixed: 在ie8之前,用setAttribute方法为设定属性时,会有以下bug: "class", "for", "name", "style"这些属性都会不成功(亦或者说不能达到预期,比如setAttribute(“class”,”mystyleName”)会在element上设置attribute,但是并没有达到我们改变className目的),在IE8中已经修复。

获取iframe的window对象:

   
function getIframeWindow(iframeElement){
    //IE || w3c
    return iframeElement.contentWindow || iframeElement.contentDocument.parentWindow;
}

判定页面是否存在iframe

   
window.onload = function(){
 var hasFrame =  typeof window.frameElement === “undefined”
 alert(hasFrame)
}

原理是,没iframe的时候window.frameElement为null。

(iframe)使用总结
url:http://hi.baidu.com/liulin0712/blog/item/e801ee3fc71a86c97c1e7146.html
2009年12月25日 星期五 15:36

在Web开发过程中,为了提高页面架构层次的清晰性和灵活性,应对复杂的页面布局,使用嵌入式框架iframe可能是最有效的解决办法。如果布局比较复杂或页面层次较多,则可能会用到嵌套多层的iframe,然而iframe并不会根据页面高度自动调整自身高度,为了屏蔽滚动条提高视觉效果,就需要使用javascript代码使iframe自动调整高度。
    1、单层情况,假设在A.aspx页面的某个位置嵌入页面B.aspx,则在A页面中需使用一个嵌入框架iframeA,其示例代码如下:
        <head>
                 ...
                <script type="text/javascript">
                        //iframeName:框架ID
                        function SetIframeSize(iframeName)
                           {
                                var iframe = document.getElementById(iframeName);
                                try
                                   {
                                        var bHeight = iframe.contentWindow.document.body.scrollHeight;
                                        var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
                                        //据说这两个高度可能不一样
                                        var height = Math.max(bHeight, dHeight);
                                         iframe.height =     height;
                                       }catch (ex){}
                         }
                </script>
        </head>
        <body>
                 ...
                <tr>
                        <td>
                                <iframe id="iframeA" name="iframeA" scrolling="no" frameborder="0" src="B.aspx" width="100%"

οnlοad="SetIframeSize('iframeA');"></iframe>
                        </td>
                <tr>
                 ...
        </body>
         ...

2、嵌套两层情况,假设A.aspx页面通过嵌入式框架iframeA嵌入页面B.aspx,页面B.aspx又通过嵌入式框架iframeB嵌入页面C.aspx,其中A.aspx示例代码和单层情况一样,B.aspx页面的示例代码如下:

...
        <head>
                 ...
                <script type="text/javascript">
                        //iParentFrameName:父框架ID
                        //iframeName:框架ID
                        function SetIframeSize(iParentFrameName,iframeName)
                       {
                                var iframe = document.getElementById(iframeName);
                                try
                               {
                                        var bHeight = iframe.contentWindow.document.body.scrollHeight;
                                        var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
                                        //据说这两个高度可能不一样
                                        var height = Math.max(bHeight, dHeight);
                                         iframe.height =     height;
                                        //更新父框架高度
                                         SetIframeSize2(iParentFrameName)
                                 }catch (ex){}
                         }

//iframeName:框架ID
                        function SetIframeSize2(iframeName) {
                                var iframe = window.parent.parent.document.getElementById(iframeName);
                                try
                             {
                                        var bHeight = iframe.contentWindow.document.body.scrollHeight;
                                        var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
                                        var height = Math.max(bHeight, dHeight);
                                         iframe.height =     height;
                              }catch (ex){}
                         }        
                </script>
        </head>
        <body>
                 ...
                <tr>
                        <td>
                                <iframe id="iframeB" name="iframeB" scrolling="no" frameborder="0" src="C.aspx" width="100%"

οnlοad="SetIframeSize('iframeA','iframeB');"></iframe>
                        </td>
                <tr>
                 ...
        </body>
         ...

其中代码
        var iframe = window.parent.parent.document.getElementById(iframeName);
    window指C.aspx,window.parent指B.aspx,window.parent.parent指A.aspx
    事实上如果没有特别需要(比如B.aspx页面条件加载C.aspx页面)下,A.aspx中iframeA可以不要onload事件。

3、嵌套多层情况
    多层嵌层以两层情况为例类推,同上没有特别需要,只设最后一级iframe的onload事件。

iframe 用法总结相关推荐

  1. HTML IFRAME 用法小总结

    iframe是框架的一种形式,也比较常用到,下面是对其在平时常用到属性的总结 Iframe用法,下面是一个常规的列子 <iframe border=2 frameborder=0 width=5 ...

  2. Iframe 用法的详细讲解

    Iframe 用法的详细讲解 把iframe解释成"浏览器中的浏览器"很是恰当 <iframe frameborder=0 width=170 height=100 marg ...

  3. Iframe用法的详细讲解(属性、透明、自适应高度)和html中滚动条属性设置

    Iframe 用法的详细讲解(属性.透明.自适应高度)和html中滚动条属性设置 scrollbar属性.样式详解 1. overflow内容溢出时的设置(设定被设定对象是否显示滚动条) overfl ...

  4. 学习HTML:iframe用法总结收藏

    <iframe>是框架的一种形式,也比较常用到. 一:几个例子--演示iframe的基本用法 例1: <iframe width=420 height=330 frameborder ...

  5. iframe展示html源代码,HTML DOM IFrame用法及代码示例

    HTML DOM中的IFrame对象属性用于创建和访问对象中的元素.内联框架用于将另一个文档嵌入当前HTML文档中. 用法: 它用于访问元素.var x = document.getElementBy ...

  6. HTML iframe用法

    定义和用法 iframe元素会创建包含另外一个文档的内联框架(即行内框架). 把iframe解释成"浏览器中的浏览器"很是恰当. iframe属性 1.frameborder 规定 ...

  7. iframe用法精析

    Html代码   <iframeframeborder=0width=170height=100marginheight=0marginwidth=0scrolling=nosrc=" ...

  8. Iframe 用法浅析

    解释成"浏览器中的浏览器"很是恰当 <iframe frameborder=0 width=170 height=100 marginheight=0 marginwidth ...

  9. iframe并没有错

      今天在网页中写了这么一句: <iframe src="show_image.htm" marginheight="0" marginwidth=&qu ...

最新文章

  1. JAVA数组编程教程_Java语言编程基础:数组
  2. 深度学习与芯片之间的羁绊往事
  3. base64编解码的类
  4. Docker 安装配置Tomcat
  5. Error loading WebappClassLoader解决方法
  6. c# 溢出抛异常_C#中的int是否没有溢出异常?
  7. 第十三节:使用Lombok简化你的代码
  8. limit mongodb 聚合_mongodb-$type、limit、skip、sort方法、索引、聚合
  9. QueryRunner类 的應用,以及ResultSetHandler 接口的实现类
  10. 数据结构试卷及答案(一)
  11. android ip地址扫描,如何准确扫描Android中连接到wifi的所有设备的IP和Mac地址?
  12. 对象存储osd以及存储分类
  13. 差分技术:LVDS(低电压差分信号)
  14. 【树形DP】保镖排队
  15. 浪潮云服务器安装win7系统,WIN7旗舰版操作系统中浪潮ERP_GS5.2安装说明.doc
  16. 香港流行乐黄金二十年——经典歌手(音乐人)全面回顾 一
  17. mysql phpwind_linux下的PHP+Mysql+PHPWind实现
  18. 用 HLS m3u8 及FFMPEG搭建视频点播平台
  19. android 预览和拍照成像方向不一致,Android相机预览方向深入探究
  20. c++11:std::default_delete

热门文章

  1. kubernetes之探针
  2. 芯片PIC32MZ1024ECH100 (MCHP) -- 32位高性能单片机 up to 330 DMIPS
  3. Smalltalk的变量
  4. Windows 之 win SMB(smb) 功能的开启设置和使用的简单说明
  5. word计算机桌面加密,word文档加密,怎么让word自动加密 -电脑资料
  6. 垃圾回收之G1收集过程
  7. numpy.meshgrid()理解
  8. Java虚拟机讲解 与 搞垮Java虚拟机
  9. Visio 2016 和 SharePoint Designer 2013 来创建工作流并将其发布到 SharePoint 2016 网站而无需任何代码
  10. python下载文件并改名_用 Python 给下载的 B 站视频文件批量改名