简体   繁体   English

我何时应该在窗口与文档与document.body上观察Javascript事件?

[英]When should I observe Javascript events on window vs. document vs. document.body?

I'm using prototype.js for my web app, and I have everything running on Chrome, Safari, and Firefox. 我正在将prototype.js用于我的网络应用程序,并且我已经在Chrome,Safari和Firefox上运行了所有内容。 I am now working on IE8 compatibility. 我现在正致力于IE8的兼容性。

As I've been debugging in IE, I've noticed that there are Javascript events for which I have previously set an observer on the window, eg 正如我在IE中调试的那样,我注意到有一些Javascript事件,我以前在窗口上设置了一个观察者,例如

Event.observe(window, eventType, function () {...});

(where eventType might be "dom:loaded" , "keypress" , etc.) and it works just fine in Chrome/Safari/Firefox. (其中eventType可能是"dom:loaded""keypress"等),它在Chrome / Safari / Firefox中运行良好。 However, in IE the observer never fires. 然而,在IE中,观察者永远不会发射。

In at least some cases I could get this to work on IE by instead placing the observer on something other than window , eg document (in the case of "dom:loaded" ) or document.body (in the case of "keypress" ). 至少在某些情况下,我可以通过将观察者放在window以外的其他东西上来使用它来工作,例如document (在"dom:loaded"的情况下)或document.body (在"keypress"的情况下) 。 However, this is all trial-and-error. 但是,这都是反复试验。

Is there some more systematic way to determine where to place these observers such that the results will be cross-browser compatible? 是否有更系统的方法来确定这些观察者的位置,以便结果将跨浏览器兼容?

(This is not a super-comprehensive answer, but it seems to work out empirically -- so hopefully these rules of thumb will be helpful to others.) (这不是一个非常全面的答案,但它似乎在经验上有效 - 所以希望这些经验法则对其他人有帮助。)

  • In general, register events on document , not window . 通常,在document上注册事件,而不是window Webkit and mozilla browsers seem to be happy with either, but IE doesn't respond to most events registered on the window, so you need to use document to work with IE Webkit和Mozilla浏览器似乎都很满意,但是IE不响应窗口上注册的大多数事件,所以你需要使用document来处理IE

  • Exception: resize , and events related to loading, unloading, and opening/closing should all be set on the window. 例外: resize ,并且应该在窗口上设置与加载,卸载和打开/关闭相关的事件。

  • Exception to the first exception: dom:loaded must be set on document in IE. 第一个异常的例外: dom:loaded必须在IE中的document上设置。

  • Another exception: When detecting keystrokes under Mozilla with find-as-you-type enabled, set your key event observers on the window , not the document . 另一个例外:当在启用了find-as-you-type的情况下检测Mozilla下的击键时,在window而不是document上设置关键事件观察者。 If you do the latter, the find-as-you-type seems to block the event. 如果你使用后者,find-as-you-type似乎会阻止事件。

The various browsers' object documentation (eg window on MSDN, document on MDC) define which events are supported on the object. 各种浏览器的对象文档(例如MSDN上的window ,MDC上的document )定义了对象支持的事件。 You could start there. 你可以从那里开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM