我知道这应该不难,但我在谷歌上找不到答案。

我想执行一段javascript,将从任何元素上清除焦点,而不知道提前哪个元素的焦点。它必须在firefox 2和更现代的浏览器上运行。

有什么好办法吗?


当前回答

我更喜欢document.activeElement?document.activeElement.blur()。

我正在使用vue & react:在我的情况下,我可以在组件之间的任何地方调用它,它将删除焦点。

其他回答

.focus()然后.blur()在你的页面上任意的东西。因为只有一个元素可以有焦点,所以焦点被转移到那个元素,然后被移除。

在使用TypeScript时,这里提供的答案都不是完全正确的,因为您可能不知道所选择的元素的类型。

因此,最好这样做:

if (document.activeElement instanceof HTMLElement)
    document.activeElement.blur();

此外,我不鼓励使用已被接受的答案中提供的解决方案,因为由此产生的模糊不是官方规范的一部分,并且随时可能破坏。

答:document.activeElement

你可以使用document.activeElement.blur()

如果你需要支持Firefox 2,你也可以使用这个:

function onElementFocused(e)
{
    if (e && e.target)
        document.activeElement = e.target == document ? null : e.target;
} 

if (document.addEventListener) 
    document.addEventListener("focus", onElementFocused, true);

我更喜欢document.activeElement?document.activeElement.blur()。

我正在使用vue & react:在我的情况下,我可以在组件之间的任何地方调用它,它将删除焦点。

dummyElem.focus()哪里dummyElem是一个隐藏对象(例如有负zIndex)?