简体   繁体   English

如何通过专注于文档来模糊所有内容?

[英]How do I blur everything by focusing on the document?

using Jquery/javascript使用 Jquery/javascript

Is it: $(document).focus()?是:$(document).focus()?

The .focus() method on a jQuery-wrapped element will bind to the onfocus event if a function is passed as the first parameter, or trigger attached event handlers with no parameter.如果函数作为第一个参数传递,或者触发不带参数的附加事件处理程序,则 jQuery 包装元素上的.focus()方法将绑定到onfocus事件。

I'm not sure why you're trying to do what you're trying to do, but if you're trying to blur the currently active element, no matter what element it is, you can use:我不确定您为什么要尝试做您想做的事情,但是如果您要模糊当前活动的元素,无论它是什么元素,都可以使用:

document.activeElement.blur();

This isn't advised though, as doing so will reset the tabbing order and potentially annoy keyboard-navigating users.但不建议这样做,因为这样做会重置标签顺序并可能会惹恼键盘导航用户。

UPDATE: In Typescript you should just cast to HTMLElement like this:更新:在 Typescript 中,您应该像这样转换为HTMLElement

(document.activeElement as HTMLElement).blur();
// or
(<HTMLElement>document.activeElement).blur();

Original answer is below.原始答案如下。


The accepted answer won't work in TypeScript because document.activeElement is an Element type, not HTMLElement , so it doesn't technically support blur() .接受的答案在 TypeScript 中不起作用,因为document.activeElementElement类型,而不是HTMLElement ,因此它在技术上不支持blur() The below method is kind of hacky but it works properly.下面的方法有点hacky,但它可以正常工作。

Adapted from this answer :改编自这个答案

const tmp = document.createElement('input');
document.body.appendChild(tmp);
tmp.focus();
document.body.removeChild(tmp);

$().method() fires the listeners associated with that method. $().method()触发与该方法关联的侦听器。 If you need to call functions on dom elements, index the jQuery object.如果您需要在 dom 元素上调用函数,请索引 jQuery 对象。

ie IE

$(document)[0].focus()

Although why you wouldn't just use document.focus is probably a question worth answering.尽管您为什么不只使用document.focus可能是一个值得回答的问题。

If the objective is to remove the focus on any form field element you can use this:如果目标是消除对任何表单字段元素的关注,您可以使用它:

$(':focus').blur();

If you don't have jQuery, you can use plain JavaScript:如果你没有 jQuery,你可以使用纯 JavaScript:

let elem = document.querySelector(':focus');
if(elem ) {
  elem .blur();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM