BT9034: 僅 IE 和 Opera 支持 HTMLFrameElement 和 HTMLIFrameElement 的 document 屬性

標準參考

根據 DOM-2 中的描述,HTMLFrameElement 和 HTMLIFrameElement 都沒有 'document' 屬性。html

關於 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'。ui

受影響的瀏覽器

IE6 IE7 IE8 Operaspa

問題分析

分析如下兩組測試代碼,他們分別嘗試獲取 HTMLFrameElement 和 HTMLIFrameElement 的 'document' 屬性:code

<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'。htm

注:以上測試與文檔模式無關。對象

解決方案

使用 HTMLFrameElement 或 HTMLIFrameElement 對象的 contentWindow 屬性獲得該框架頁的 window 對象應用,再訪問其下的 document 對象。blog

即把上述測試代碼的 '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>
相關文章
相關標籤/搜索