当目标元素已移动时,不会触发点击处理程序 [英] Click handler is not triggered when target element has been moved

查看:80
本文介绍了当目标元素已移动时,不会触发点击处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下演示 https://stackblitz.com/edit/angular-pur1dt

我具有反应式表单控件,其中包含同步验证器和无效时在字段下方显示的错误消息.

I have reactive form control with sync validator and error message shown below the field when it is invalidated.

当控件失去焦点时,将触发验证.控件下方是带有单击处理程序的按钮.问题是,当我单击按钮时,控件失去了焦点,发生了验证,显示了错误消息,并将按钮向下移动.据说这会阻止单击处理程序执行.有任何建议为什么会发生这种情况以及如何解决该问题?

Validation is triggered when control loses focus. Below the control there is a button that has a click handler. The problem is that when I click the button, control loses focus, validation happens, error message shown and moves the button down. And supposedly this prevents click handler from executing. Any suggestions why this happens and how to fix the issue?

我已经用演示更新了演示.注意:仅输入下方的按钮会重现该问题.首次单击后,标题将不会更新.

I've updated the demo with comments. Note: only button below the input will reproduce the issue. The title wont be updated after you click it for the first time.

推荐答案

问题似乎与DOM事件的触发顺序有关

The issue seem to relate to DOM events triggering order

根据MDN:

当指向设备按钮(通常是一个 鼠标的主按钮)被按下并释放到单个元素上.

The click event is fired when a pointing device button (usually a mouse's primary button) is pressed and released on a single element.

https://developer.mozilla.org/zh-CN/docs/Web/Events/click

在给定的示例中,元素在您输入blur的那一刻就移动了-因为验证会立即发生,显示错误并重新定位按钮.

In the given example the element moves the moment you blur the input -- because the validation happens instantly, reveals the error and repositions the button.

因此,当鼠标在按钮上方时,鼠标会向下,但在鼠标按下会重新定位按钮.因此,不会在按钮上触发click

Therefore mouse is down when while over the button, but when its up -- the button is repositioned. So click wont be triggered on the button

有几种解决方法:

  • mousedown上延迟错误显示
  • 隐藏错误,直到mousedownmouseup都发生,如果按钮上发生了mousedown
  • on mousedown delay the error reveal
  • hide the error until both mousedown and mouseup happened, if mousedown happened on the button
  • etc

这是mousedown事件处理的示例 https://jsfiddle.net/gjbgqqpo/

Here's an example with mousedown event handling https://jsfiddle.net/gjbgqqpo/

希望这会有所帮助:)

这篇关于当目标元素已移动时,不会触发点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆