检测由 Tab 键启动的焦点?

Detect focus initiated by tab key?(检测由 Tab 键启动的焦点?)
本文介绍了检测由 Tab 键启动的焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测元素的焦点事件,但前提是它是由用户按 Tab 键启动的.例如:

I want to detect the focus event of an element, but only if it was initiated by the user pressing the tab key. For example:

<input type="text" id="foo" />
<input type="text" id="detect" />

如果用户关注 #foo 并按下 Tab,我希望在 #detect 成为焦点(或焦点事件内的条件为真).相反,如果用户只是单击 #detect 字段来聚焦它,我不希望事件触发(或者我希望聚焦事件调用中的条件为 false).

If the user is focused on #foo and presses Tab, I want the event to fire once #detect becomes focused (or a conditional inside the focus event to be true). Conversely, if the user simply clicks on the #detect field to focus it, I do not want the event to fire (or I want the conditional inside the focus event call to be false).

我不想使用 #foo 的 keydown 事件并检查是否按下了 tab 键,因为我希望该方法独立于任何其他元素.

I don't want to use the keydown event of #foo and check if the tab key was pressed, as I want the approach to be independent of any other element.

我查看了以下代码的控制台输出,但没有注意到两种聚焦方法之间的真正区别:

I looked through the console output of the following code, but couldn't notice any real differences between the two methods of focusing:

$('#detect').on('focus', function(e){
   console.log(e); 
});

(小提琴)

这可能以相对简单的方式完成吗?

Is this possible to accomplish in a relatively simple way?

推荐答案

我知道您已经接受了答案,但您可以使用以下方法测试按下的按钮:

I know you have accepted an answer but you could test the button pressed using the following:

$('#detect').on('focus', function(e){
    $(window).keyup(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 9) {
           alert('I was tabbed!');
        }
    });
});

http://jsfiddle.net/LPGLm/1/

改变监听器:

$(window).keyup(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 9 && $('#detect:focus').length) {
        alert('I was tabbed!');
    }
});

http://jsfiddle.net/LPGLm/7/

这篇关于检测由 Tab 键启动的焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)