Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - Detect focus initiated by tab key?

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" />

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

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); 
});

(fiddle)

Is this possible to accomplish in a relatively simple way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

Edit: change the listener around:

$(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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...