“contentDocument”对于 iframe(甚至旧的“frame”元素)究竟代表什么?它相当于“html”元素还是“body”元素?它有什么用?所有浏览器都支持此属性吗?
iframe 的 contentDocument
DOM 级别 2 中引入的 Document 类型的 contentDocument,只读,此框架包含的文档(如果有并且可用),否则为 null。
从 DOM iframe 元素,脚本可以通过 contentWindow 属性访问包含的 HTML 页面的 window 对象。contentDocument 属性指的是 iframe 内的文档元素(这相当于 contentWindow.document),但 IE8 之前的 Internet Explorer 版本不支持。
此页面或框架包含的文档
此属性是 Windows Internet Explorer 8 中的新属性
因此,要获取您可以使用的 body 元素的 innerHTML
iframe.contentDocument.getElementsByTagName("body")[0]
或者
iframe.contentDocument.body
在今天的浏览器中。
contentDocument是获取 iframe 或框架Document对象的标准化方法。它与在 iframe 中运行的 JavaScript 将通过document.
正如其他答案中所述,IE 直到版本 8 才支持它,但确实支持Window通过contentWindow. <body>因此,获取 iframe元素的跨浏览器方式是:
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var iframeBody = iframeDoc.body;
请注意,如果 iframe 不是来自与主文档相同的域,浏览器安全限制将阻止以这种方式或任何其他方式访问其文档对象。
contentDocument表示 iframe(DOM 对象)的文档。它不等同于html因为文档有自己的属性,但是如果您键入:
myFrame.contentDocument.body
你会得到身体本身。
所有浏览器都支持它,稍作修改:供 Internet Explorer 使用
myFrame.contentWindow.document
享受,妮莉