Question:
Is it feasible to focus on a
Background:
A
<code class="html"><div id="tries">You have 3 tries left</div></code>
And an attempt is made to focus on this
<code class="javascript">document.getElementById('tries').focus();</code>
However, the focus is not being applied.
Answer:
Yes, it is possible to focus on a
<code class="html"><div tabindex="0">You have 3 tries left</div></code>
A tabindex of 0 places the tag within the natural tab order of the page. Higher numbers assign a specific order of priority, with 1 being the first, 2 being the second, and so on.
Additionally, a tabindex of -1 makes the
Here's a code example illustrating this:
<code class="javascript">document.getElementById('tries').onclick = function () { document.getElementById('scripted').focus(); };</code>
<code class="css">div:focus { background-color: Aqua; }</code>
<code class="html"><div>Element X (not focusable)</div> <div tabindex="0">Element Y (user or script focusable)</div> <div tabindex="-1" id="scripted">Element Z (script-only focusable)</div> <div id="test">Set Focus To Element Z</div></code>
The above is the detailed content of Can I Use JavaScript's `focus()` Function on a `` Element?. For more information, please follow other related articles on the PHP Chinese website!