onclick() and onblur() ordering issue

前端 未结 6 1927
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 14:52

I have an input field that brings up a custom drop-down menu. I would like the following functionality:

  • When the user clicks anywhere outside the input field,
6条回答
  •  隐瞒了意图╮
    2020-12-04 15:47

    onClick should not be replaced with onMouseDown.

    While this approach somewhat works, the two are fundamentally different events that have different expectations in the eyes of the user. Using onMouseDown instead of onClick will ruin the predictability of your software in this case. Thus, the two events are noninterchangeable.

    To illustrate: when accidentally clicking on a button, users expect to be able to hold down the mouse click, drag the cursor outside of the element, and release the mouse button, ultimately resulting in no action. onClick does this. onMouseDown doesn't allow the user to hold the mouse down, and instead will immediately trigger an action, without any recourse for the user. onClick is the standard by which we expect to trigger actions on a computer.

    In this situation, call event.preventDefault() on the onMouseDown event. onMouseDown will cause a blur event by default, and will not do so when preventDefault is called. Then, onClick will have a chance to be called. A blur event will still happen, only after onClick.

    After all, the onClick event is a combination of onMouseDown and onMouseUp, if and only if they both occur within the same element.

提交回复
热议问题