BT9034: 仅 IE 和 Opera 支持 HTMLFrameElement 和 HTMLIFrameElement 的 document 属性

标准参考

根据 DOM-2 中的描述,HTMLFrameElement 和 HTMLIFrameElement 都没有 'document' 属性。

关于 HTMLFrameElement 对象的详细信息,请参考 DOM-2 Interface HTMLFrameElement 中的内容。

关于 HTMLIFrameElement 对象的详细信息,请参考 DOM-2 Interface HTMLIFrameElement 中的内容。

问题描述

仅 IE Opera 支持使用 HTMLFrameElement.document 和 HTMLIFrameElement.document 属性得到框架页的 HTMLDocument 对象。这个属性是非标准的。

造成的影响

如果试图通过 HTMLFrameElement 和 HTMLIFrameElement 对象的 'document' 属性获得框架页的 HTMLDocument 对象,在 FrireFox Chrome Safari 中将得到 'undefined'。

受影响的浏览器

IE6 IE7 IE8 Opera

问题分析

分析以下两组测试代码,他们分别尝试获取 HTMLFrameElement 和 HTMLIFrameElement 的 'document' 属性:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script>
window.onload=function(){
  alert(document.getElementById("frame").document);
};
</script>
</head>
<frameset>
  <frame id="frame" src="_content.html" />
</frameset>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script>
window.onload=function(){
  alert(document.getElementById("iframe").document);
};
</script>
</head>
<body>
  <iframe id="iframe" src="_content.html"></iframe>
</body>
</html>

以上测试用例中,只有 IE6 IE7 IE8 Opera 对两者均会得到一个 HTMLDocument 对象(即框架内页面的 document 对象),而其他浏览器返回的是 'undefined'。

注:以上测试与文档模式无关。

解决方案

使用 HTMLFrameElement 或 HTMLIFrameElement 对象的 contentWindow 属性得到该框架页的 window 对象应用,再访问其下的 document 对象。

即把上述测试代码的 'XXX.document' 更改为 'XXX.contentWindow.document',如:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script>
window.onload=function(){
  alert(document.getElementById("iframe").contentWindow.document);
};
</script>
</head>
<body>
  <iframe id="iframe" src="_content.html"></iframe>
</body>
</html>
原文地址:https://www.cnblogs.com/wawahaha/p/5106086.html