2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

focusin/focusoutでメニュー外をクリックしたら勝手に閉じるドロップダウンメニュー

Posted at

【CSS4】:focus-withinでクリックタイプのドロップダウンメニュー?
↑先日のこれは、
http://caniuse.com/#search=focus-within
このように、現状実務では使えません。
仕方ないのでjavascriptで実装してみましょう。
focusin/focusoutイベントを使います。
http://caniuse.com/#search=focusin
これは、focus/blurイベントのバブルアップする版です。:focus-withinと似てるね!
Firefoxは次期バージョンである52からとなっていますが、試してみたら51でもなんかいけた。
というわけで現状、モダンブラウザでは問題なく使えそうです。

dropdown.html
<div tabindex="-1" class="dropdown">めにう
  <ul>
    <li><a href="/hoge">hoge</a></li>
    <li><a href="/fuga">fuga</a></li>
    <li><a href="/piyo">piyo</a></li>
  </ul>
</div>
focusin.css
.dropdown > ul {
  display: none;
}
.dropdown.focused > ul {
  display: block;
}
focusin.js
$(".dropdown")
  .on("focusin", function() {
    $(this).addClass("focused");
  })
  .on("focusout", function(ev) {
    if($(ev.relatedTarget).closest(this).length) { return; }
    $(this).removeClass("focused");
  });

ごみん.closest()のとこがめんどくさそうだったのでjQuery使ってしまいました。
event.relatedTargetには次にフォーカスを受け取る要素が入ります。
要するに focusout の発火原因となった要素がメニュー内のものだったらメニューの表示を継続するという処理です。

blurイベントだとrelatedTarget受け取れないんじゃないかなあ。試してないのでわからんけど。

2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?