0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

横に長い表がある画面で、右端に開閉式のパネルを実装しました。
パネルを開いたら見出しにフォーカスを移したいのですが、そのとき表まで横にスクロールすると、見ていた列の位置がずれてしまいます。

フォーカス可能な要素に focus() を呼ぶと、ブラウザーは既定でその要素を表示するためにスクロールします。

今回のパネルはすでに画面の右端に見えているので、focus() に伴うスクロールを preventScroll: true で抑えることにしました。

実際の挙動

次のコードを focus.html として保存し、ブラウザーで開いてください。Tab でボタンに移動し、Enter で押すと挙動を比べられます。
見出しの tabindex="-1" は、通常の Tab キーの移動順に加えず focus() でフォーカスを移すために記載しています。

focus.html
<!doctype html>
<html lang="ja">
<meta charset="utf-8">
<title>フォーカスと横スクロール</title>
<style>
  #box {
    display: flex;
    align-items: center;
    gap: 480px;
    width: 240px;
    overflow-x: auto;
    white-space: nowrap;
    border: 1px solid;
  }
</style>

<button onclick="compare(false)">指定なし</button>
<button onclick="compare(true)">指定あり</button>
<div id="box">
  <span>左端</span>
  <h2 id="heading" tabindex="-1">フォーカス先</h2>
</div>

<script>
  const box = document.getElementById('box')
  const heading = document.getElementById('heading')

  function compare(preventScroll) {
    heading.blur()
    box.scrollLeft = 0
    if (preventScroll) {
      heading.focus({ preventScroll: true })
    } else {
      heading.focus()
    }
  }
</script>
</html>

「指定なし」を選択している時は、右の見出しまでスクロールします。
「指定あり」を選択している時は、左端の表示を保つので、このサンプルでは見出しが枠の外に残ります。

どちらの場合もフォーカス先は見出しです。コンソールのdocument.activeElement で確認できます。

おわりに

preventScroll: true を使うと、フォーカスが移ってもブラウザーはその要素が見える位置までスクロールしません。そのため、フォーカスは当たっているのに、画面上ではその場所が見えないこともあります。

preventScroll: trueを使うときは、フォーカス先が画面上で見えているかも確認しておくとよいと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?