检查输入字段是否在vanilla JavaScript中具有焦点

Sim*_*ger 12 html javascript focus input

使用jQuery,我可以测试输入字段是否具有焦点如下:

if ($("...").is(":focus")) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

不使用jQuery我该怎么做?

ric*_*ges 18

这个问题在这里得到了解答:Javascript检测输入是否集中

取自以上答案:

this === document.activeElement // where 'this' is a dom object
Run Code Online (Sandbox Code Playgroud)

  • 使用示例:`if (document.activeElement.tagName === "INPUT") console.log("输入已聚焦");` (3认同)