JavaScript 中有什么方法可以聚焦文档(内容区域)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6976486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:05:03  来源:igfitidea点击:

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

javascriptfocus

提问by Timwi

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.

有没有办法在 JavaScript 中将焦点设置到文档,即内容区域?document.focus()似乎没有做任何事情。

回答by RobG

In HTML 4.01, focusis 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.

HTML 4.01 中焦点仅在诸如表单控件和链接之类的元素的上下文中讨论。在HTML 5 中,它被更广泛地讨论。但是,焦点对文档的作用主要取决于浏览器。

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

它也得到了很好的支持

回答by Timwi

It seems that the following code works...

似乎以下代码有效...

document.activeElement.blur();