0
0

More than 3 years have passed since last update.

カスタム要素を使った、タブフォーカスの抑止

Last updated at Posted at 2021-02-10

はじめに

ダイアログを表示した場合、タブで後ろのコンテンツにフォーカスが行かないようにしたいなど、
タブによるフォーカスの遷移を抑止したい場合がかなりあると思います。
そんなときに役に立つ小技を見つけたので共有します。

環境

  • Chrome, Firefoxで確認

やり方

CustomElementを用意

shadow domの中に子要素を表示するだけのカスタム要素を用意します。

customElements.define(
    "custom-element", 
    class CustomElement extends HTMLElement {
        constructor(){
            super()
            this.attachShadow({mode: "open"})
            this.shadowRoot.appendChild(document.createElement("slot"))
        }
    }
)

使う

<div>
    <h3>親のカスタム要素にtabindex="-1"</h3>
    <custom-element tabindex="-1">
        <input type="text">
        <input type="text">
        <input type="text">
    </custom-element>
</div>
<div>
    <h3>親の要素にtabindex="-1"</h3>
    <div tabindex="-1">
        <input type="text">
        <input type="text">
        <input type="text">
    </div>
</div>

tabindex.gif

カスタム要素にtabindex="-1"を指定するだけでその子要素にフォーカスが行かなくなります。
たぶん仕様です。たぶん

※もっとスマートな方法があったら教えてくださいmm

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0