问题
Check the test page here http://rickchristie.com/testfocus.html
Correct me if I'm wrong:
onfocus
happens when the element gains focus.onblur
happens when the element loses the focus.
In Firefox 3.6.12 (tested on mac and windows), using onblur
without onfocus
works fine. However when an input element has both onfocus
and onblur
element, it gets weird:
- When you click at the input,
onblur
is fired instead ofonfocus
. - Right after
onblur
,onfocus
fires immediately. - You can't type anything in the textbox.
Other browsers (Safari, Opera) works as expected. Is this a bug? Is it just me or is everybody using Firefox experiencing this?
Update
This behavior seems to happen only when onblur
and onfocus
contains alert
- not when I use something like window.log
.
回答1:
When the alert box opens, focus is removed from the text box. Notice that the "BLUR" alert box opens right on top of the "FOCUS" alert box (the latter opened first), so that's why it looks like onblur
fired before onfocus
.
Look at my test page, which increments a counter when either event handler is called and also adds a second alert box after both of the others. It seems that Firefox actually starts executing the blur handler as soon as the alert box from the focus handler opens, despite the conceptually single-threaded model of the browser. However, when the first (focus) alert box is closed, the second (blur) alert box has to also be closed before the third (after focus) alert box opens.
I don't know Firefox why does it the way it does. Chrome keeps firing the focus handler again and again, and Opera, Safari, and IE do it the way you would expect — not taking away the text box's focus.
EDIT: I've found https://bugzilla.mozilla.org/show_bug.cgi?id=31889 and will be posting this test case there – apparently it used to be even worse.
来源:https://stackoverflow.com/questions/4236477/firefox-weird-onblur-behavior-3-6-12