Home  >  Q&A  >  body text

JavaScript focus clearing method

<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>
P粉231112437P粉231112437400 days ago376

reply all(2)I'll reply

  • P粉662614213

    P粉6626142132023-08-22 14:16:10

    .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.

    reply
    0
  • P粉348088995

    P粉3480889952023-08-22 12:57:31

    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:

    function onElementFocused(e)
    {
        if (e && e.target)
            document.activeElement = e.target == document ? null : e.target;
    } 
    
    if (document.addEventListener) 
        document.addEventListener("focus", onElementFocused, true);

    reply
    0
  • Cancelreply