我如何检查我的元素ID是否有焦点? [英] How can I check if my Element ID has focus?

查看:70
本文介绍了我如何检查我的元素ID是否有焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < div id =

myIDtabindex = - 1>一些文字< / div>

我想创建一个处理程序来检查该div是否具有焦点,以及何时评估true / focus在div上,做一些事情(在下面的例子中,打印控制台日志): getElementById('#myID')。hasFocus()){
$(document).keydown(function(event){
if(event.which === 40){
console。 log('keydown pressed')
}
});
}

在控制台中收到错误消息:



TypeError:无法读取属性'hasFocus'为null



任何想法我在这里做错了吗?也许我通过div ID的方式?

解决方案

比较 document.activeElement 与您要检查的元素焦点。如果它们是相同的,则该要素是重点;

  //虚拟元素
var dummyEl = document.getElementById('myID') ;

//检查焦点
var isFocused =(document.activeElement === dummyEl);

hasFocus 文档的一部分 ;没有这样的DOM元素的方法。

另外, document.getElementById 不使用<$ c $在 myID 的开始部分使用c>#。改变它:

  var dummyEl = document.getElementById('#myID'); b 




var dummyEl = document.getElementById('myID');

如果您想使用CSS查询,您可以使用 querySelector (和 )。


Let's say I have the following div that gets focus after a certain condition is met:

<div id="myID" tabindex="-1" >Some Text</div>

I want to create a handler that checks whether or not that div has focus, and when it evaluates to true/focus is on the div, do something (in the example below, print a console log):

if (document.getElementById('#myID').hasFocus()) {
            $(document).keydown(function(event) {
                if (event.which === 40) {
                    console.log('keydown pressed')
                }
            });
        }

I'm getting an error message in the console that says:

TypeError: Cannot read property 'hasFocus' of null

Any idea what I'm doing wrong here? Maybe the way I'm passing the div Id?

解决方案

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is part of the document; there's no such method for DOM elements.

Also, document.getElementById doesn't use a # at the beginning of myID. Change this:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

If you'd like to use a CSS query instead you can use querySelector (and querySelectorAll).

这篇关于我如何检查我的元素ID是否有焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆