gpt4 book ai didi

javascript - 如果另一个元素已经聚焦,如何聚焦 body 元素?

转载 作者:行者123 更新时间:2023-12-02 23:10:05 27 4
gpt4 key购买 nike

如果另一个元素已经获得焦点,如何以编程方式将焦点放在 body/document.body 元素上?

调用 document.body.focus() 似乎不起作用,可能是因为 body 不可聚焦。

MDN

The HTMLElement.focus() method sets focus on the specified element, if it can be focused.

最佳答案

如果您首先对当前聚焦的元素调用 .blur(),然后调用 window.focus,Chrome 和 Firefox 都会聚焦 document.body 元素() 紧随其后。

完整解决方案(TypeScript):

    private focusBody = () => {
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
window.focus();
};

关于javascript - 如果另一个元素已经聚焦,如何聚焦 body 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408482/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com