为什么在发生模糊事件时 console.log 不能 运行?

Why the console.log can't run when blur event occur?

 
function  fix(event){
    console.log("hello");        
} 
document.addEventListener("blur",fix,false);
 
 
<table>
 <tr>
        <td>class</td>
        <td><input type="text" class="data"></td>
 </tr>
 <tr>
        <td>name</td>
        <td><input type="text" class="data"></td>
 </tr>
</table>
 

这么简单的js函数
我希望 console.log 在模糊事件发生时执行,无论鼠标的焦点离开哪个输入,hello 显示在控制台上。
我的修复函数有什么问题?

blur 不会冒泡,所以如果您使用这样的事件委托,它将不可见 - 如果它的侦听器直接附加到,您只会看到 blur 事件有问题的元素。如果您想使用事件委托,请改为监听 focusout 事件:

function fix(event) {
  console.log("hello");
}
document.addEventListener("focusout", fix, false);
<table>
  <tr>
    <td>class</td>
    <input type="text" class="data"></td>
  </tr>
  <tr>
    <td>name</td>
    <td><input type="text" class="data"></td>
  </tr>
</table>

另一种可能性是在捕获阶段监听 blur 事件:

function fix(event) {
  console.log("hello");
}
document.addEventListener("blur", fix, true);
//                                     ^^^^
<table>
  <tr>
    <td>class</td>
    <input type="text" class="data"></td>
  </tr>
  <tr>
    <td>name</td>
    <td><input type="text" class="data"></td>
  </tr>
</table>

true 作为您的 useCapture 参数传递。如 MDN Docs for Event Delegation 中所述,可能还需要使用聚焦。

function fix(event) {
  console.log("hello");
}
document.addEventListener("blur", fix, true);
<table>
  <tr>
    <td>class</td>
    <td><input type="text" class="data"></td>
  </tr>
  <tr>
    <td>name</td>
    <td><input type="text" class="data"></td>
  </tr>
</table>

MDN Docs for General Event Info 中所述,不同的浏览器监听事件的方式各不相同:

Note: The value of Document.activeElement varies across browsers while this event is being handled (bug 452307): IE10 sets it to the element that the focus will move to, while Firefox and Chrome often set it to the body of the document.