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
}
to destinguish wether the focus is inside of one of my elements. Can you show me a jQuery-free way of doing it?
使用 CSS:focus伪类querySelectorAll()
setTimeout(function(){
  if (document.querySelectorAll("div :focus").length === 0)
    console.log("not focused");
  else
    console.log("focused")
}, 2000);<div>
  <input type="text">
</div>您可以Node.contains为此使用本机DOM方法。
el.contains(document.activeElement);
将检查是否activeElement是的后代el。如果要检查多个元素,则可以使用some函数进行迭代。
根据您的情况,使用事件可能会更高效。
在这种情况下,您可以使用focusin和focusout事件。
const el = document.getElementById("myEl");
el.addEventListener("focusin", () => console.log("focus!"));
el.addEventListener("focusout", () => console.log("blur!"));
请注意,在focusout事件期间,这document.activeElement将是文档正文。要解决此问题,您可以使用FocusEvent.relatedTarget.
可以使用 Element 的matches() 方法和一个简单的选择器字符串,如下所示:
let hasFocused = elem.matches(':focus-within:not(:focus)');
let focusedOrHasFocused = elem.matches(':focus-within');
如果您遇到模糊事件后document.activeElement返回<body>元素的问题,您只需使用 setTimeout() 包装它,它将返回正确的元素。
handleBlur() {
    setTimeout(() => { 
        console.log(document.activeElement); // this actually return active/focused element
    });
}
如果您独立使用它而没有超时
handleBlur() {
    console.log(document.activeElement); // this is returning <body> element
}
omr*_*don -1
要检索所选元素,您可以使用:
let activeElement = document.activeElement
要检查特定元素:
let elem = document.getElementById('someId');
let isFocused = (document.activeElement === elem);