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

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

问题描述

考虑以下演示 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/en-US/docs/Web/Events/click

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

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

有几种解决方法:

  • on 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天全站免登陆