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, frameBorder, height, 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。
对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元素,需要注意以下两点:
- 必须先获取指定iframe的document
- 对于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修正,虽然速度非常慢。详见这里