问题
There is a textarea
element which converts itself into a div
when onblur
event happens on that same textarea
. There is also a button
which has its onclick
property set to function f
.
If one is writing in the textarea
and then clicks on a button
, f
is fired, but also onblur
event handler is triggered. Is there some order rules in this case, or the two handler functions may fire in random order?
回答1:
I created a jsfiddle here: http://jsfiddle.net/z5SEp/
The events for latest Chrome seem to be:
mousedown
blur
mouseup
click
Although I could not find any documentation to rely on, it would make sense to me that blur is fired after mousedown, but before mouseup. Mousedown causes blur, but you could leave your mouse button down for an extended period of time and still cause a blur.
The order of click events will always be 1. mousedown 2. mouseup 3. click. The blur makes sense to be after mousedown but before mouseup.
More things to keep in mind
If you trigger the button click like this: $('button').trigger('click');
, then the blur event will not fire, and focus will remain on the textarea.
回答2:
In this scenario, the blur will always fire first because blur is triggered as soon as the mouse button goes down elsewhere on the page. So when the mouse goes down on your button, the textarea's blur event is fired first. As the mouse comes up, the button's click event is fired.
来源:https://stackoverflow.com/questions/22867022/onblur-vs-onclick-timing