【问题标题】:Input field blur event not get triggering while set display none for parent element in firefox在Firefox中为父元素设置显示无时输入字段模糊事件未触发
【发布时间】:2026-02-12 23:25:01
【问题描述】:

我的 Div 元素中有一个输入字段。我已经使用鼠标聚焦文本框。 按任意键时,我将使用 display: none 隐藏 div 元素 虽然元素被隐藏,但输入元素的模糊事件在 chrome 中触发但在 Firefox 和 IE 浏览器中未触发模糊事件。

请运行以下示例供您参考。

https://www.w3schools.com/code/tryit.asp?filename=FWDH988538TX

重现步骤:

运行示例。打开控制台窗口 使用鼠标聚焦文本框。 当光标位于文本框内时,单击任意键。 检查控制台。会触发模糊事件。

但这在 Firefox 中不起作用

【问题讨论】:

  • w3schools.com/code/tryit.asp?filename=FWDH988538TX 在 Firefox60.0.2 上为我工作
  • 您是否正确执行了复制步骤?打开控制台,然后使用鼠标聚焦文本框->单击回车键->检查控制台(在 firefox 和 chrome 中)
  • 是的,你说得对,我注意到在Firefox中你必须点击外部
  • 我的版本火狐62.0.3
  • 其他浏览器,不用在外面点进去就可以了。但是在Firefox中它失败了。为什么?如何解决?

标签: javascript html


【解决方案1】:

以下演示将使用 Chrome 或 Firefox 显示此行为:

  • 当用户尝试输入<input> 时,环绕<input><label> 变为display:none

    • 如果一个事件从<input> 触发,它应该是一个失去焦点的事件(例如blurfocusoutchange...)。不管是什么,回调函数都应该将两项记录到控制台:

      1. called

      2. <body></body> // 作为活动元素 bug 452307

Firefox 无法在blur 事件上触发,但它在input 事件上触发。在演示中,有一个名为:addListener() 的自定义函数,它可以在单个节点上注册多个事件。该函数在<input> 上注册blurinput

演示

<html>

<head>
  <style>
    #box {
      height: 500px;
      width: 500px;
      border: 1px solid red;
      display: block;
      position: relative;
    }
  </style>
</head>

<body>
  <form id='form'>
    <fieldset id='box'>
      <input id='key' type="text" />
    </fieldset>
  </form>
  <script>
    var ui = document.forms[0].elements;
    var box = ui.box;
    var key = ui.key;

    box.addEventListener('keydown', closeBox);

    function closeBox(e) {
      e.target.style.display = 'none';
    }

    addListeners(key, 'input blur', triggerOnExit);

    function triggerOnExit(e) {
      console.log('called');
      console.log(document.activeElement);
    }

    function addListeners(node, list, callBack) {
      list.split(' ').forEach(function(e) {
        node.addEventListener(e, callBack);
      });
    }
  </script>

</body>

</html>

【讨论】:

    【解决方案2】:

    问题在于不同的浏览器选择以不同的顺序调用事件处理程序。 SP 最简单的解决方案是检查 OnWrapperClose 方法上的 activElement

    var a = document.getElementById('blur');
    function onWrapperClose(e) {
                            document.getElementById('Wrapper').style.display = 'none';
                            console.log(document.activeElement);
    
                        if(document.activeElement === a){
    // do what you wanted to do on blur function   
                    }
    

    你可以 在 Firefox 上它提供 activeElemnt,而在 Chrome 上你会得到 body 标签,可能你想添加父 div 以便于调试。

    【讨论】:

    • 在这种情况下,我不会将 document.activeElement 作为正文。输入将永远保持为活动元素。
    • 以与您给出的相同步骤运行相同的代码,它将活动元素作为主体
    • 或者我们可以再尝试一件事,添加一个父 div 看看我们是否获得了焦点