30秒学会 JavaScript 片段 · 2023年11月18日

30秒学会 JavaScript 片段 – Select the focused DOM element with JavaScript

Finding the currently focused DOM element is trivial in modern CSS, using the :focus selector. You can also use it in JavaScript, in combination with Document.querySelector() to find the focused element. Yet, there’s an even easier way to get the currently focused element in JavaScript, using the Document.activeElement property.

代码实现

const focusedElement = document.activeElement;
// `focusedElement` is the currently focused element

Note that focusable elements vary depending on browser and operating system. Additionally, you should remember that focus and selection (i.e. content highlighting) are not the same thing.

翻译自:https://www.30secondsofcode.org/js/s/select-focused-dom-element