简体   繁体   English

JavaScript 事件处理程序竞赛

[英]JavaScript event handler race

If I have a text field with a registered onblur event handler and a button with a registered onmouseup event handler, which one of those two functions will run sooner and why?如果我有一个带有注册的onblur事件处理程序的文本字段和一个带有注册的onmouseup事件处理程序的按钮,这两个函数中的哪一个将运行得更快,为什么?

To make my question clearer, let's suppose the focus is currently on the text field and I want to click on the button.为了让我的问题更清楚,让我们假设当前焦点在文本字段上,我想单击该按钮。

Will there be any difference between various Internet browsers?各种网络浏览器之间会有什么区别吗?

Edit编辑

Especially tricky seems the onmousedown event when it's registered with the button, whilst the text field has an onblur event registered with it.当使用按钮注册时, onmousedown事件似乎特别棘手,而文本字段则注册了一个onblur事件。

The spec says blur must be fired when focus leaves the element (after taking focus away), but I don't see any explicit statement about when that must occur relative to the event causing the focus to be moved away.规范说blur必须在焦点离开元素时触发(在将焦点移开之后),但我没有看到任何关于何时必须发生相对于导致焦点移开的事件的明确声明。

Certainly the mouseup will happen much later (in computer terms), as first you have to mousedown .当然mouseup会发生得更晚(用计算机术语来说),因为首先你必须mousedown

I would have expected blur to fire prior to even the mousedown , but I would have been wrong: According to experimentation , mouseup is after, but mousedown is before.我原以为blur会在mousedown之前触发,但我错了:根据实验mouseup在之后,但mousedown在之前。 I tested that using Chrome 26, Opera 12.15, Firefox 20, IE8, and IE9 — and if you can get those five to agree on a behavior, it's likely to be consistent in others... :-) My suspicion is that this is because if you prevent the default action of the mousedown , focus never moves away from the text field: Example .我使用 Chrome 26、Opera 12.15、Firefox 20、IE8 和 IE9 进行了测试——如果你能让这五个人就某个行为达成一致,那么其他人可能会保持一致……:-) 我怀疑这是因为如果您阻止mousedown的默认操作,则焦点永远不会离开文本字段:示例 (This behavior is consistent across four of those five browsers, with IE8 not preventing the focus change — meaning IE7 and 6 probably don't, either.) So while it seems odd, it does kind of make sense. (这种行为在这五个浏览器中的四个浏览器中是一致的,IE8 不会阻止焦点更改——这意味着 IE7 和 6 可能也不会。)所以虽然看起来很奇怪,但它确实有点道理。

As always, test with the browsers you intend to support.与往常一样,使用您打算支持的浏览器进行测试。

Just save the timestamp when starting只需在启动时保存时间戳

var start = new Date().getTime();

and then接着

var elapsed = new Date().getTime() - start;

into the handler.进入处理程序。

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

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