HTMLElement.focus()
HTMLElement.focus()
メソッドは、指定された要素にフォーカスを設定できる場合、フォーカスを設定します。 フォーカスされた要素は、デフォルトでキーボードや同様のイベントを受け取る要素です。
構文
element.focus(options); // Object parameter
パラメーター
options
省略可- フォーカスプロセスの側面を制御するオプションを提供するオプションのオブジェクト。 このオブジェクトには、次のプロパティが含まれる場合があります。
-
preventScroll
省略可- ブラウザーがドキュメントをスクロールして、新しくフォーカスされた要素を表示するかどうかを示す
Boolean
の値。preventScroll
の値がfalse
(デフォルト)の場合、ブラウザーは要素をフォーカスした後、その要素をスクロールして表示します。preventScroll
がtrue
に設定されている場合、スクロールしません。
例
テキストフィールドにフォーカスする
JavaScript
focusMethod = function getFocus() {
document.getElementById("myTextField").focus();
}
HTML
<input type="text" id="myTextField" value="テキストフィールド">
<p></p>
<button type="button" onclick="focusMethod()">クリックしてテキストフィールドにフォーカスしてください!</button>
結果
ボタンにフォーカスする
JavaScript
focusMethod = function getFocus() {
document.getElementById("myButton").focus();
}
HTML
<button type="button" id="myButton">クリックしてください!</button>
<p></p>
<button type="button" onclick="focusMethod()">クリックしてボタンにフォーカスしてください!</button>
結果
focusOption でフォーカスする
JavaScript
focusScrollMethod = function getFocus() {
document.getElementById("myButton").focus({preventScroll:false});
}
focusNoScrollMethod = function getFocusWithoutScrolling() {
document.getElementById("myButton").focus({preventScroll:true});
}
HTML
<button type="button" onclick="focusScrollMethod()">クリックしてボタンにフォーカスしてください!</button>
<button type="button" onclick="focusNoScrollMethod()">クリックしてスクロールせずにボタンにフォーカスしてください!</button>
<div id="container" style="height: 1000px; width: 1000px;">
<button type="button" id="myButton" style="margin-top: 500px;">クリックしてください!</button>
</div>
結果
仕様
ノート
mousedown
イベントハンドラから HTMLElement.focus()
を呼び出す場合は、event.preventDefault()
を呼び出して、フォーカスがその HTMLElement
から離れないようにする必要があります。
ブラウザーの互換性
BCD tables only load in the browser
関連情報
- 要素からフォーカスを取り除く DOM メソッド
HTMLElement.blur()
。 - 現在フォーカスされている要素がどれであるかを知るための
document.activeElement
。