Is there any way in JavaScript to focus the document (content area)?

后端 未结 2 981
庸人自扰
庸人自扰 2020-12-09 08:26

Is there any way to set focus to the document, i.e. the content area, in JavaScript? document.focus() doesn’t seem to do anything.

相关标签:
2条回答
  • 2020-12-09 09:08

    It seems that the following code works...

    document.activeElement.blur();
    
    0 讨论(0)
  • 2020-12-09 09:11

    In HTML 4.01, focus is only discussed in the context of elements such as form controls and links. In HTML 5, it is discussed much more widely. However, how focus works for documents is mostly browser dependent.

    You might try:

    // Give the document focus
    window.focus();
    
    // Remove focus from any focused element
    if (document.activeElement) {
        document.activeElement.blur();
    }
    

    It is very well supported as well.

    0 讨论(0)
提交回复
热议问题