javascript 如何检测JS中的焦点更改事件?

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

How to detect focus changed event in JS?

javascript

提问by CharlesX

I want to write a function, this function can detect whether the focus is on the certain element.If the focus is on the element, I call the onfocus()function, and if not on the element, I do nothing.How can I do this?

我想写一个函数,这个函数可以检测焦点是否在某个元素上。如果焦点在该元素上,我调用该onfocus()函数,如果不在该元素上,我什么都不做。我该怎么做?

回答by imbondbaby

Many different ways to do this.

许多不同的方法来做到这一点。

Here is 2 examples:

这里有2个例子:

Solution #1:

解决方案#1:

You could use simple inline onblurfunction to see if that certain element is focused out. This is probably the simplest way to do it.

您可以使用简单的内联onblur函数来查看某个元素是否被突出显示。这可能是最简单的方法。

<input type="text" onblur="javascript:alert('You have focused out');" />

Demo

演示

Solution #2:

解决方案#2:

HTML:

HTML:

<input type="text" />

JQuery:

查询:

var selectedInput = null;
$(function() {
    $('input').focus(function() {
        selectedInput = this;
    }).blur(function(){
        selectedInput = null;
        alert("You have focused out");
    });
});

Demo

演示

If you want multiple, you could use:

如果你想要多个,你可以使用:

$('input, textarea, select').focus(function() {

Credits

学分

You could use blurand focusfunctions to see if that certain element is focused.

您可以使用blurfocus函数来查看某个元素是否被聚焦。