javascript 更改选项卡(onfocus/onblur)时如何从activeElement中移除焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21017189/
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 to remove focus from activeElement when changing tabs (onfocus/onblur)?
提问by frequent
I'm trying to remove focus from a (jQuery Mobile) text input when a user switches tabs on desktop. While I can correctly identify the activeElement in the below console, I cannot edit any of its properties or remove its focus.
当用户在桌面上切换选项卡时,我试图从 (jQuery Mobile) 文本输入中移除焦点。虽然我可以在下面的控制台中正确识别 activeElement,但我无法编辑其任何属性或移除其焦点。
This is what I'm doing:
这就是我正在做的:
// inside some init method
window.onfocus = function () {
// triggers
console.log(document.activeElement);
if (document.activeElement.tagName !== "BODY") {
console.log("clear focus");
document.activeElement.blur();
document.activeElement.className = "FOOBAR";
}
};
When I'm on a form and focus a text input, then switch to another tab and go back to the tab with the form, the event listener triggers and my still active input is correctly logged. However that's it... I can't blur or edit any of the elements properties.
当我在一个表单上并聚焦一个文本输入,然后切换到另一个选项卡并返回带有表单的选项卡时,事件侦听器会触发并且我仍然处于活动状态的输入被正确记录。然而就是这样......我不能模糊或编辑任何元素属性。
Question:
How do I correctly remove focus from the active element either on window.onfocus
or window.onblur
?
问题:
如何正确地从活动元素上移除焦点 onwindow.onfocus
或window.onblur
?
Thanks!
谢谢!
PS: it also does not work with jQuery:
PS:它也不适用于 jQuery:
$(window).on("focus", function () {
$(document.activeElement).blur();
});
and I'm looking for a JavaScript only solution.
我正在寻找一个只使用 JavaScript 的解决方案。
EDIT:document.activeElement.blur()
works fine from the console, but not from my listener.
编辑:document.activeElement.blur()
从控制台工作正常,但不是从我的听众。
回答by frequent
Ok. This works:
行。这有效:
window.onblur = function () {
document.activeElement.blur();
};
So it seemed the blur worked fine, because if I console activeElemnt
beforeand aftermy call to blur()
it switched from an INPUT to the BODY tag. Correctly, my body has it's class set to FOOBAR
. Problem for me was that the text element still retained focus, but I assume this is due to some handler inside jQuery Mobile.
所以看起来模糊效果很好,因为如果我activeElemnt
在调用它之前和之后进行控制台blur()
从 INPUT 切换到 BODY 标签。正确地,我的身体将它的类设置为FOOBAR
. 我的问题是文本元素仍然保持焦点,但我认为这是由于 jQuery Mobile 内部的一些处理程序。
The above solution works the other way around. I remove focus of the activeElement
when the user switches a tab. Works.
上述解决方案相反。activeElement
当用户切换选项卡时,我会移除焦点。作品。