javascript Angularjs $document[0].activeElement 而不是 $document.activeElement

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19035006/
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-10-27 14:08:15  来源:igfitidea点击:

Angularjs $document[0].activeElement instead of $document.activeElement

javascriptangularjsangularjs-directive

提问by Anirudhan J

I am writing a placeholder directive using angularjs.

我正在使用 angularjs 编写占位符指令。

On the click handler I want to check if the element and document.activeElement are the same.

在单击处理程序上,我想检查元素和 document.activeElement 是否相同。

I tried to use $docuemnt.activeElementfor that but it was always undefined. But when I used $document[0].activeElementI am getting the currently active element.

我试图使用$docuemnt.activeElement它,但它总是undefined. 但是当我使用时,$document[0].activeElement我得到了当前活动的元素。

Is $document[0].activeElementis the right way to access the currently active element? Or am doing something wrong?

$document[0].activeElement访问当前活动元素的正确方法吗?还是做错了什么?

回答by iConnor

No, $documentis a wrapped version of document, it is wrapped using jQlite which is a tiny version of jQuery, so $documentdoesn't have any method called activeElementbecause documentis inside $document, So you'll have to use

不,$document是 的包装版本document,它是使用 jQlite包装的,jQlite 是 jQuery 的一个小版本,所以$document没有调用任何方法,activeElement因为document在里面$document,所以你必须使用

$document[0].activeElement

Or

或者

document.activeElement

You could also create a global variable that is a wrapped version of activeElement like so.

您还可以创建一个全局变量,它是 activeElement 的包装版本,就像这样。

var $activeElement = angular.element(document.activeElement);
$activeElement.attr('focused', 'yes'); // Example usage

回答by Tyler Moses

Just as an additional note is you use the above answer with:

正如附加说明一样,您将上述答案用于:

$document[0].activeElement

$document[0].activeElement

Then you are actually an array of active elements so you need to use:

那么你实际上是一个活动元素数组,所以你需要使用:

$document[0].activeElement[0]

$document[0].activeElement[0]

or

或者

angular.element($document[0].activeElement)[0]

angular.element($document[0].activeElement)[0]