简体   繁体   English

“模糊”事件无缘无故被触发?

[英]“blur” event being triggered for no reason?

I have 2 elements. 我有两个要素。 The first element has a blur event, and the second element has a mousedown event. 第一个元素具有blur事件,第二个元素具有mousedown事件。 The mousedown event on the second element returns the focus to the first element, but blur on the first element is triggered for some reason, even if the first element wasn't focused before mousedown ing the second element. 第二个元素上的mousedown事件将焦点返回到第一个元素,但是由于某些原因触发了第一个元素上的blur ,即使第一个元素在mousedown第二个元素之前没有聚焦。

Why does this happen? 为什么会这样? Is this (somehow) desired behaviour, or is this some kind of bug? 这是(某种程度上)期望的行为,还是某种错误?

<!DOCTYPE html>
<html>
<head>
<title>Bug?</title>
</head>
<body>

<input type="text" />
<br /><br />
<button>Click me to focus on the input</button>
<br /><br />
<input type="text" />

<script type="text/javascript">
    document.getElementsByTagName('input')[0].addEventListener('blur', function(e){
        console.log('blur', e);
    });

    document.getElementsByTagName('button')[0].addEventListener('mousedown', function(e){
        console.log('mousedown', e);

        document.getElementsByTagName('input')[0].focus();
    });
</script>
</body>
</html>

https://jsfiddle.net/rsh5aopg/ https://jsfiddle.net/rsh5aopg/

This is not a bug, the event sequence is: 这不是错误,事件序列为:

mousedown
blur
mouseup
click

When you press the button, the mousedown event is triggered. 当您按下按钮时,将触发mousedown事件。 Within that listener, you focus the first input. 在该侦听器中,您将重点放在第一个输入上。 Naturally, after the mousedown event, the blur event happens. 自然,在mousedown事件之后,就会发生模糊事件。 This takes away focus from first input and you see the blur listener code execute. 这使焦点从第一次输入移开,您将看到模糊侦听器代码执行。

You can either add e.preventDefault() to the mousedown event, or use either mouseup or click as those both happen after the blur. 您可以将e.preventDefault()添加到mousedown事件中,也可以使用mouseupclick因为两者都在模糊之后发生。 Either way, the first input will still have focus as you desire. 无论哪种方式,第一个输入都将根据您的需要具有焦点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM