Javascript - Firefox behavior blur by mouse click.

2019-06-17 06:00发布

问题:

Scenario: display alert message onblur (or onchange) as a part of javascript field validation.

User action with onblur:
1) click inside input
2) click outside the input
3) close the alert message
4) move mouse around

Result: mousedown seems to be performed at the position where you clicked out before the alert came up -- elements on the page get selected when you move the mouse around.
Note: This doesn't happen when tabbing out of the input.

Demo: http://jsfiddle.net/s9sc4/

<body>
Click inside the input and then outside of it.
<input type="text" onblur="alert('Close this alert message and move the mouse around.');" />
TEST TEST TEST
</body>

Reproduced on:
Firefox 28 and 29 Platforms: Windows 7 & 8 and OSX Mavericks (4 different machines).
Using a clean Firefox profile made no difference.

QUESTION: Is this a bug, or default behavior? Chrome, Safari and IE don't behave like this.
If it's as designed, do I need to do something with preventDefault or cancel bubbling/stop propagation after the alert to stop this behavior?

回答1:

You can try to add:

window.getSelection().removeAllRanges();

This will solve your issue.

To answer your question: this seems to be a bug of FireFox and needs a workaround. What happens is FireFox messed up the priority of events where focus is set first, prior to onblur. Browsers who don't have the bug will not fire the focus event when onblur occurs.

DEMO



回答2:

That's interesting. This feels like a bug. I did get around it be calling setTimeout, and then calling alert:

<input ... onblur="setTimeout(function() { alert(...); }, 0);">