如何通过关注文档来模糊一切?

TIM*_*MEX 16 javascript jquery

使用Jquery/javascript

是:$(document).focus()?

And*_*y E 36

如果函数作为第一个参数传递,则.focus()jQuery包装元素上的方法将绑定到onfocus事件,或触发没有参数的附加事件处理程序.

我不确定你为什么要尝试做你想做的事情,但是如果你想模糊当前活动的元素,无论它是什么元素,你都可以使用:

if ("activeElement" in document)
    document.activeElement.blur();
Run Code Online (Sandbox Code Playgroud)

但不建议这样做,因为这样做会重置标签顺序并可能使键盘导航用户烦恼.

  • Best首先检查`if('documentE''在文档中)`,因为它并不是所有浏览器都支持. (2认同)
  • [`document.activeElement`](https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement) 是一个 [`Element`](https://developer.mozilla.org/ en-US/docs/Web/API/Element) 类型,而不是 [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement),所以从技术上讲它并不支持 `blur()`。TypeScript 不允许使用它。 (2认同)

vai*_*dil 9

更新:在 Typescript 中你应该像HTMLElement这样转换:

(document.activeElement as HTMLElement).blur();
// or
(<HTMLElement>document.activeElement).blur();
Run Code Online (Sandbox Code Playgroud)

原始答案如下。


接受的答案在 TypeScript 中不起作用,因为它document.activeElement是一种Element类型,而不是HTMLElement,所以它在技术上不支持blur()。下面的方法有点hacky,但它可以正常工作。

改编自这个答案

const tmp = document.createElement('input');
document.body.appendChild(tmp);
tmp.focus();
document.body.removeChild(tmp);
Run Code Online (Sandbox Code Playgroud)