How to check if element has focused child using javascript?

Mar*_*ger 6 html javascript jquery focus

I'm trying to remove all jQuery from my code. Until now I used

if($(selector).find(':focus').length === 0){
  //focus is outside of my element
}else{
  //focus is inside my element
}
Run Code Online (Sandbox Code Playgroud)

to destinguish wether the focus is inside of one of my elements. Can you show me a jQuery-free way of doing it?

Moh*_*mad 8

使用 CSS:focus伪类querySelectorAll()

setTimeout(function(){
  if (document.querySelectorAll("div :focus").length === 0)
    console.log("not focused");
  else
    console.log("focused")
}, 2000);
Run Code Online (Sandbox Code Playgroud)
<div>
  <input type="text">
</div>
Run Code Online (Sandbox Code Playgroud)


Nor*_*ern 8

您可以Node.contains为此使用本机DOM方法。

el.contains(document.activeElement);
Run Code Online (Sandbox Code Playgroud)

将检查是否activeElement是的后代el。如果要检查多个元素,则可以使用some函数进行迭代。


Jes*_*end 8

根据您的情况,使用事件可能会更高效。

在这种情况下,您可以使用focusinfocusout事件。

const el = document.getElementById("myEl");
el.addEventListener("focusin", () => console.log("focus!"));
el.addEventListener("focusout", () => console.log("blur!"));
Run Code Online (Sandbox Code Playgroud)

请注意,在focusout事件期间,这document.activeElement将是文档正文。要解决此问题,您可以使用FocusEvent.relatedTarget.


Nag*_*tán 7

可以使用 Element 的matches() 方法和一个简单的选择器字符串,如下所示:

let hasFocused = elem.matches(':focus-within:not(:focus)');
let focusedOrHasFocused = elem.matches(':focus-within');
Run Code Online (Sandbox Code Playgroud)


Ada*_*cký 6

如果您遇到模糊事件后document.activeElement返回<body>元素的问题,您只需使用 setTimeout() 包装它,它将返回正确的元素。

handleBlur() {
    setTimeout(() => { 
        console.log(document.activeElement); // this actually return active/focused element
    });
}
Run Code Online (Sandbox Code Playgroud)

如果您独立使用它而没有超时

handleBlur() {
    console.log(document.activeElement); // this is returning <body> element
}
Run Code Online (Sandbox Code Playgroud)


omr*_*don -1

要检索所选元素,您可以使用:

let activeElement = document.activeElement
Run Code Online (Sandbox Code Playgroud)

要检查特定元素:

let elem = document.getElementById('someId');

let isFocused = (document.activeElement === elem);
Run Code Online (Sandbox Code Playgroud)