打开时HTML对话框焦点按钮元素 [英] HTML dialog focusing button element when opened

查看:109
本文介绍了打开时HTML对话框焦点按钮元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个<dialog>,我正在通过JS打开.出于演示目的,我的对话框中只有一个<button>元素.

I currently have a <dialog> which I am opening via JS. For demonstration purposes, my dialog has a single <button> element within it.

我的问题是,当我使用.showModal()打开对话框时,模态中的按钮由于某种原因变得聚焦.请参见下面的问题示例:

My issue is, when I open the dialog using .showModal(), the button within the modal gets focused for some reason. See example of issue below:

const dialog = document.querySelector("#dialog");
document.querySelector("#open-btn").addEventListener('click', () => {
  dialog.showModal();
});

document.querySelector("#close-btn").addEventListener('click', () => {
  dialog.close();
});

#close-btn:focus {
  background: red;
}

<button id="open-btn">Open</button>
<dialog id="dialog">
  <button id="close-btn">&times;</button>
</dialog>

如您所见,当对话框打开时,对话框中按钮的背景将得到:focus样式的应用,表明它已聚焦.

As you can see, when the dialog is opened, the background of the button within the dialog gets the :focus styles applied, showing that it is focused.

我的问题是:为什么会这样?我的预期行为是打开对话框,而打开对话框时按钮未对准焦点.我知道我可以通过编程方式.blur()关闭按钮,但这感觉就像是在隐藏"该问题,而不是解决实际上引起该问题的原因.

My question is: Why is this happening? My expected behaviour would be for the dialog to open and for the button to not be focused when opening the dialog. I'm aware that I can .blur() the close button programatically, but that feels like I'm just "hiding" the issue rather than addressing the thing that's actually causing it.

注意:最新版本的Google Chrome浏览器(版本81.0.4044.138)中存在此问题

Note: This issue is present in the latest version of Google Chrome (Version 81.0.4044.138)

推荐答案

这似乎是标准中定义的默认行为,用于从

This is seems default behavior defined in the standard to focus the modal subtree once its rendered, from the HTML live standard:

  1. 运行对话框的主题聚焦步骤.

如果要保持这种状态并防止按钮聚焦,只需在按钮上触发blur()事件,我就尝试使用

If you want to keep it like this and prevent the button from focus just trigger blur() event on the button, I tried to use inert and autofocus attributes but they doesn't seems to work work, so I think you have to stick with .blur() implementation:

const dialog = document.querySelector("#dialog");
document.querySelector("#open-btn").addEventListener('click', () => {
  dialog.showModal();
  document.getElementById('close-btn').blur();
});

document.querySelector("#close-btn").addEventListener('click', () => {
  dialog.close();
});

#close-btn:focus {
  background: red;
}

<button id="open-btn">Open</button>
<dialog id="dialog">
  <button id="close-btn" inert="false" autofocus="false">&times;</button>
</dialog>

这篇关于打开时HTML对话框焦点按钮元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆