Javascript 如何检查我的元素 ID 是否具有焦点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36430561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:03:42  来源:igfitidea点击:

How can I check if my Element ID has focus?

javascriptjqueryhtml

提问by Kode_12

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

假设我有以下 div 在满足特定条件后获得焦点:

<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):

我想创建一个处理程序来检查该 div 是否具有焦点,并且当它评估为 true/焦点在 div 上时,执行某些操作(在下面的示例中,打印控制台日志):

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

类型错误:无法读取 null 的属性“hasFocus”

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

知道我在这里做错了什么吗?也许我传递 div Id 的方式?

回答by Florrie

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

document.activeElement与要检查焦点的元素进行比较。如果它们相同,则元素为焦点;否则,它不是。

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

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

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

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

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

此外,document.getElementById不使用#之初myID。改变这个:

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).

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

回答by Michael

If you want to use jquery $("..").is(":focus").

如果你想使用 jquery $("..").is(":focus")

You can take a look at this stack

你可以看看这个堆栈

回答by Oen44

Use document.activeElement

document.activeElement

Should work.

应该管用。

P.S getElementById("myID")not getElementById("#myID")

PSgetElementById("myID")不是getElementById("#myID")

回答by Eihwaz

This is a block element, in order for it to be able to receive focus, you need to add tabindexattribute to it, as in

这是一个块元素,为了让它能够获得焦点,你需要tabindex给它添加属性,如

<div id="myID" tabindex="1"></div>

Tabindex will allow this element to receive focus. Use tabindex="-1"(or indeed, just get rid of the attribute alltogether) to disallow this behaviour.

Tabindex 将允许此元素获得焦点。使用tabindex="-1"(或者实际上,只是完全摆脱该属性)来禁止这种行为。

And then you can simply

然后你可以简单地

if ($("#myID").is(":focus")) {...}

Or use the

或者使用

$(document.activeElement)

As been suggested previously.

正如之前所建议的。

回答by Narendra1414

Write below code in script and also add jQuery library

在脚本中编写以下代码并添加 jQuery 库

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

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you...

谢谢...