HTML DOMボタンのautofocusプロパティは、要素のautofocusプロパティに関連付けられています。ボタンのオートフォーカスプロパティは、ページの読み込み時にHTMLドキュメントのボタンにフォーカスを合わせるかどうかを指定するために使用されます。
構文
以下は、-
の構文です。
ボタンのオートフォーカスプロパティの設定-
buttonObject.autofocus = true|false
ここで、true | falseは、ページが読み込まれたときではなく、指定された入力ボタンにフォーカスを合わせるかどうかを指定します。
正しい −入力ボタンにフォーカスが移る 誤り − 入力ボタンにフォーカスがありません。
例
HTMLDOMボタンのオートフォーカスプロパティの例を見てみましょう-
<!DOCTYPE html>
<html>
<body>
<button type="button" id="MyButton" autofocus>BUTTON</button>
<p>Click the below button to know if the input button above automatically gets the focus on page load or not</p>
<button onclick="buttonFocus()">CLICK IT</button>
<p id="Sample"></p>
<script>
function buttonFocus() {
var x = document.getElementById("MyButton").autofocus;
if(x==true)
document.getElementById("Sample").innerHTML="The input button does get focus on page load";
else
document.getElementById("Sample").innerHTML="The input button does not get focus on
page load";
}
</script>
</body>
</html> 出力
これにより、次の出力が生成されます-
CLICKITボタンをクリックすると-
上記の例では-
IDが「MyButton」でオートフォーカスプロパティが有効になっているボタンがあります-
<button type="button" id="MyButton" autofocus>BUTTON</button>
次に、CLICK ITボタンを使用してbuttonFocus()関数を実行します-
<button onclick="buttonFocus()">CLICK IT</button>
buttonFocus()関数は、getElementById()メソッドを使用してボタン要素を取得し、ブール値であるオートフォーカス値を取得して、変数xに割り当てます。条件ステートメントを使用して、オートフォーカス値がtrueとfalseであるかどうかを確認し、それに応じてID「Sample」が関連付けられた
要素に適切なテキストを表示します。
function buttonFocus() {
var x = document.getElementById("MyButton").autofocus;
if(x==true)
document.getElementById("Sample").innerHTML="The input button does get focus on page load";
else
document.getElementById("Sample").innerHTML="The input button does not get focus on page load";
}