如何从Document对象获取Window对象?

Jor*_*ren 56 html javascript document

我能得到,window.document但我怎么能得到document.window?我需要知道如何在所有浏览器中执行此操作.

ken*_*bec 102

你可以选择,document.defaultView如果你确定它是一个窗口,它可以在IE 9之前跳过Microsoft浏览器.

  • 是.请记住,根据规范,`document.defaultView`不必与`window`是同一个对象(事实上,它在某些旧客户端中是不同的,例如:Safari 2.x) (6认同)
  • doc.parentWindow || doc.defaultView,它适用于旧的IE和Safari (3认同)

Bil*_*ese 18

跨浏览器解决方案很复杂,这里是dojo的做法(来自window.js :: get()):

// In some IE versions (at least 6.0), document.parentWindow does not return a
// reference to the real window object (maybe a copy), so we must fix it as well
// We use IE specific execScript to attach the real window reference to
// document._parentWindow for later use
if(has("ie") && window !== document.parentWindow){
    /*
    In IE 6, only the variable "window" can be used to connect events (others
    may be only copies).
    */
    doc.parentWindow.execScript("document._parentWindow = window;", "Javascript");
    //to prevent memory leak, unset it after use
    //another possibility is to add an onUnload handler which seems overkill to me (liucougar)
    var win = doc._parentWindow;
    doc._parentWindow = null;
    return win; //  Window
}

return doc.parentWindow || doc.defaultView; //  Window
Run Code Online (Sandbox Code Playgroud)

has("ie")为IE返回true(否则返回false)


Kev*_*son -6

Window 对象是 JavaScript 层次结构中的顶级对象,因此只需将其称为 window

编辑:Promote JS努力 之前的原始答案。 Mozilla 开发者网络上的JavaScript 技术概述说道:

在浏览器环境中,这个全局对象就是window对象。

编辑2: 在阅读了作者对其问题的评论(并获得了反对票)后,这似乎与 iframe 的文档窗口有关。查看window.parentwindow.top并比较它们以推断您的文档窗口。

if (window.parent != window.top) {
  // we're deeper than one down
}
Run Code Online (Sandbox Code Playgroud)

  • 在“open()”之后,新窗口的“window”是除“opener”之外的另一个“窗口”。如果您从某个函数收到“文档”(或任何“节点”),您可能需要原始窗口。(哇,这已经很老了。) (8认同)