iframe元素用法總結

鴨脖發表於2013-12-10

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,height, allowTransparency

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, style, onbeforedeactivate, 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, contentEditable, document, 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 = 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完以後才能獲取;

如果頁面沒有 doctype ,a 上的 target="frameName" 在FF裡就沒效果...

控制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中是不繫結任何事件的!例子參見的另一篇博文

獲取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頁面的高度

var idoc = getIframeWindow.document;
var iheight = Math.max(idoc.body.scrollHeight,idoc.documentElement.scrollHeight);

原理是,沒iframe的時候window.frameElement為null。

用document.domain+iframe實現Ajax跨子域:這裡

清空iframe內容,不保留歷史:

w.location.replace('about:blank');

IE6下iframe.src="about:blank"在https協議下會出現問題,需要用javascript:false修正,雖然速度非常慢。詳見這裡