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
Is there any way in JavaScript to focus the document (content area)?
提问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();