Javascript 你如何清除javascript中的焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2520650/
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
How do you clear the focus in javascript?
提问by Andres
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 element it is on without knowing ahead of time which element the focus is on. It has to work on firefox 2 as well as more modern browsers.
我想执行一段 javascript,它将从它所在的任何元素清除焦点,而无需提前知道焦点在哪个元素上。它必须适用于 Firefox 2 以及更现代的浏览器。
Is there a good way to do this?
有没有好的方法可以做到这一点?
回答by jps
Answer: document.activeElement
---edit----
- -编辑 - -
Technically: document.activeElement.blur()
技术上: document.activeElement.blur()
----edit 2----
----编辑2----
function onElementFocused(e)
{
if (e && e.target)
document.activeElement = e.target == document ? null : e.target;
}
if (document.addEventListener)
document.addEventListener("focus", onElementFocused, true);
回答by Kevin Reid
.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.
.focus()然后.blur()在您的页面上任意添加其他内容。由于只有一个元素可以拥有焦点,因此它会被转移到该元素然后被移除。
回答by pwnzor1337
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:
在 IE9 上工作出错 - 如果活动元素是文档正文,它会模糊整个浏览器窗口。最好检查一下这种情况:
if (document.activeElement != document.body) document.activeElement.blur();
回答by wilcobrouwer
None of the answers provided here are completely correct when using TypeScript, as you may not know the kind of element that is selected.
使用 TypeScript 时,此处提供的答案都不是完全正确的,因为您可能不知道所选元素的类型。
This would therefore be preferred:
因此,这将是首选:
if (document.activeElement instanceof HTMLElement)
document.activeElement.blur();
I would furthermore discourage using the solution provided in the accepted answer, as the resulting blurring is not part of the official spec, and could break at any moment.
此外,我不鼓励使用已接受答案中提供的解决方案,因为由此产生的模糊不是官方规范的一部分,并且可能随时中断。
回答by plodder
dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?
dummyElem.focus() 其中 dummyElem 是隐藏对象(例如,zIndex 为负)?
回答by kennebec
You can call window.focus();
你可以调用 window.focus();
but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.
但是移动或失去焦点必然会干扰使用 Tab 键浏览页面的任何人。
you could listen for keycode 13, and forego the effect if the tab key is pressed.
您可以监听键码 13,并在按下 Tab 键时放弃效果。
回答by bsbak
With jQuery its just: $(this).blur();
使用 jQuery,它只是: $(this).blur();

