简体   繁体   English

如何使用 JavaScript 方法 hasFocus() 不是在整个文档上而是在文档内的元素上?

[英]How to use JavaScript method hasFocus() not on whole document but on element inside document?

The definition on w3schools says that it can be done, but nowhere it's shown how. w3schools上的定义说它可以完成,但没有显示如何完成。 Snippet:片段:

if (document.getElementById(atr).hasFocus())
{
  console.log("focused");
}
else
{
  console.log("not focused");
}

I feel this is down to a misreading of the document.我觉得这归结为对文件的误读。 The doc says:医生说:

The hasFocus() method returns a Boolean value indicating whether the document (or any element inside the document) has focus. hasFocus() 方法返回一个布尔值,指示文档(或文档内的任何元素)是否具有焦点。

It is not saying that you can check either the document, or any element you want, instead it is saying it will check if the document or any element inside the document has focus这并不是说可以检查文档或您想要的任何元素,而是说它将检查文档或文档内的任何元素是否具有焦点


To propose a method with similiar functionality you can simply compare document.activeElement with your chosen element要提出具有类似功能的方法,您只需将document.activeElement与您选择的元素进行比较

// Get Element
let testElement = document.getElementById('container');

// Check against .activeElement
let isFocused = (document.activeElement === dummyEl);

document.activeElement是焦点元素,您可以通过===来检查活动元素,例如document.activeElement === document.getElementById('idOfYourHtmlElement')默认情况下,活动元素为body

To do the hasFocus method on an element, you first need to select it like so document.getElementById(elementId) and then put that in a variable to make it easier such as let testElement = document.getElementById(elementId) and then test this element with the hasFocus method as seen below要对元素执行 hasFocus 方法,首先需要像这样选择它document.getElementById(elementId)然后将其放入一个变量中以使其更容易,例如let testElement = document.getElementById(elementId)然后测试这个元素使用 hasFocus 方法,如下所示

 if(document.activeElement == testElement){ //DO something... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM