How do you clear the focus in javascript?

前端 未结 7 1761
遥遥无期
遥遥无期 2020-11-28 04:45

I know this shouldn\'t be that hard, but I couldn\'t find the answer on Google.

I want to execute a piece of javascript that will clear the focus from whatever eleme

相关标签:
7条回答
  • 2020-11-28 05:10

    You can call window.focus();

    but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

    you could listen for keycode 13, and forego the effect if the tab key is pressed.

    0 讨论(0)
  • 2020-11-28 05:11

    dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?

    0 讨论(0)
  • 2020-11-28 05:12

    With jQuery its just: $(this).blur();

    0 讨论(0)
  • 2020-11-28 05:14

    .focus() and then .blur() something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.

    0 讨论(0)
  • 2020-11-28 05:14
    document.activeElement.blur();
    

    Works wrong on IE9 - it blurs the whole browser window if active element is document body. Better to check for this case:

    if (document.activeElement != document.body) document.activeElement.blur();
    
    0 讨论(0)
  • 2020-11-28 05:20

    Answer: document.activeElement

    To do what you want, use document.activeElement.blur()

    If you need to support Firefox 2, you can also use this:

    function onElementFocused(e)
    {
        if (e && e.target)
            document.activeElement = e.target == document ? null : e.target;
    } 
    
    if (document.addEventListener) 
        document.addEventListener("focus", onElementFocused, true);
    
    0 讨论(0)
提交回复
热议问题