开发者

How do I blur everything by focusing on the document?

开发者 https://www.devze.com 2022-12-25 06:15 出处:网络
using Jquery/javascript Is it: $(document).foc开发者_StackOverflow社区us()?The .focus() method on a jQuery-wrapped element will bind to the onfocus event if a function is passed as the first paramete

using Jquery/javascript

Is it: $(document).foc开发者_StackOverflow社区us()?


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.

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:

(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(). The below method is kind of hacky but it works properly.

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. If you need to call functions on dom elements, index the jQuery object.

i.e.

$(document)[0].focus()

Although why you wouldn't just use document.focus is probably a question worth answering.


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:

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

精彩评论

暂无评论...
验证码 换一张
取 消