要素がフォーカスされているかの検出

要素がフォーカスされているかを検出するには、documentオブジェクトの読み取り専用プロパティactiveElementを使用します。

const el = document.activeElementCode language: JavaScript (javascript)

要素がフォーカスされているかを検出するには、それをdocument.activeElementと比較します。

次のコードは、.usernameクラスを持つ入力テキストがフォーカスされているかどうかをチェックします。

const el = document.querySelector('.username');
console.log(el === document.activeElement);Code language: JavaScript (javascript)
このチュートリアルは役に立ちましたか?