Shadow DOM 焦点委托:正确使用 delegatesFocus

Focus management in the shadow DOM is one of those things that is easy to get subtly wrong. You build a clean <my-button> wrapper around a native <button>, add a manual focus() override that pokes into the shadow root, ship it, and call it done. It works. But there is a cleaner way, and it has been sitting in the spec the whole time.

在 shadow DOM 中的焦点管理是那些容易微妙出错的事情之一。你围绕原生 <button> 构建一个干净的 <my-button> 包装器,添加手动 focus() 覆盖,该覆盖深入 shadow root,发布它,并认为完成了。它有效。但有一种更干净的方式,它一直存在于规范中。

That cleaner way is delegatesFocus.

那种更简洁的方式就是 delegatesFocus

What delegatesFocus Does

delegatesFocus 的作用

When you attach a shadow root with delegatesFocus: true, the browser takes on a few responsibilities that you would otherwise handle manually.

当您使用 delegatesFocus: true 附加 shadow root 时,浏览器会承担一些您原本需要手动处理的职责。

1) Clicks on the Host Element

1) 点击宿主元素

Any click on the host element (including padding areas and decorative regions outside the inner control) automatically forwards focus to the first focusable element inside the shadow root.

对宿主元素的任何点击(包括内控件外的填充区域和装饰区域)都会自动将焦点转发到影子根内的第一个可聚焦元素。

No this.shadowRoot.querySelector('button').focus() required.

无需 this.shadowRoot.querySelector('button').focus()

clicking anywhere on host forwards focus to first focusable element inside the shadow dom

clicking anywhere on host forwards focus to first focusable element inside the shadow dom

在宿主元素上任何位置点击都会将焦点转发到 Shadow DOM 内部的第一个可聚焦元素

2) Selector Matching

2) 选择器匹配

The host element matches both the :focus and :focus-within CSS pseudo-classes whenever an internal element is focused. While :focus-within normally applies to any ancestor of a focused element, the less obvious behavior occurs with :focus. When delegatesFocus: true is set, the shadow host matches :focus as if it were the focused element itself. This allows you to style the host’s focus ring using CSS alone, rather than toggling classes via JavaScript.

宿主元素在内部元素获得焦点时,会匹配 :focus:focus-within CSS 伪类。虽然 :focus-within 通常应用于焦点元素的任何祖先,但 :focus 的不太明显的表现与此不同。当设置 delegatesFocus: true 时,影子宿主会匹配 :focus,就好像它本身就是焦点元素一样。这允许您仅使用 CSS 样式化宿主的焦点环,而不是通过 JavaScript 切换类。

The host element matches both the :focus and :focus-within CSS pseudo-classes whenever an internal element is focused

It is important to note, however, that ...

开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.0. UTC+08:00, 2026-04-01 05:53
浙ICP备14020137号-1 $Carte des visiteurs$