JavaScript focus clearing method
P粉231112437
2023-08-21 19:37:32
<p>I know this shouldn't be difficult, but I can't find the answer on Google. </p>
<p>I want to execute a piece of javascript code that can clear the element where the current focus is, without knowing in advance which element the focus is on. It must work on Firefox 2 and more modern browsers. </p>
<p>Is there a good way to achieve this function? </p>
.focus()
Then select any other element.blur()
on your page. Since only one element can have focus, focus is transferred to that element and then removed.Answer:
document.activeElement
To achieve the effect you want, use
document.activeElement.blur()
If you need to support Firefox 2, you can also use the following code: