【问题标题】:Google Chrome execute HTMLElement.focus before alert get dismissed谷歌浏览器在警报被解除之前执行 HTMLElement.focus
【发布时间】:2020-05-12 09:39:47
【问题描述】:

发现 Google Chrome 与 Firefox 和 Edge 相比产生了不同的行为,具有以下 sn-p:

function lossFocus(e) {
  alert('blur'); // prompt alert
  e.focus();     // focus back to textbox
}
<input type="text" onblur="lossFocus(this);" />
<!-- NOTE: You may need to refresh this page after trigger onblur in Chrome to avoid popup loop -->

这导致lossFocus 在谷歌浏览器中被无限触发,因为focus 是在用户通过按确定或回车键关闭弹出对话框之前执行的,但其他浏览器并非如此。 (Edge 在alert 之后设法将输入字段的焦点移回)这是什么原因,这是预期的行为吗?

window.confirm() 似乎承诺在捕获用户输入后执行代码,这是否意味着如果我们希望代码仅在从弹出对话框获得用户反馈后执行,我们应该远离window.alert()

【问题讨论】:

    标签: javascript google-chrome dom dom-events


    【解决方案1】:

    目前还没有任何见解,但发现其中一种解决方法是将罪魁祸首与 nil timeout 包装起来,如下所示:

    function lossFocus(e) {
      alert('blur');
      setTimeout(() => { e.focus(); }, 0); // focus properly now after dismiss popup
    }
    &lt;input type="text" onblur="lossFocus(this);" /&gt;

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2012-01-21
      • 2014-08-27
      • 2023-02-03
      相关资源
      最近更新 更多