我想检测元素的焦点事件,但前提是它是由用户按 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 键启动的焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!