Differentiate between focus event triggered by keyboard/mouse

后端 未结 4 1455
有刺的猬
有刺的猬 2020-12-03 16:41

I\'m using jquery ui autocomplete and want to decipher between focus events triggered by keyboard interaction and mouse interaction. How would I go about this?



        
4条回答
  •  猫巷女王i
    2020-12-03 17:29

    The only way I can think of doing this is to have a handler listen in on the keypress and click events, and toggle a boolean flag on/off. Then on the focus handler of your input, you can just check what the value of your flag is, and go from there.

    Probably something like

    var isClick;
    $(document).bind('click', function() { isClick = true; })
               .bind('keypress', function() { isClick = false; })
               ;
    
    var focusHandler = function () {
        if (isClick) {
            // clicky!
        } else {
            // tabby!
        }
    }
    
    $('input').focus(function() {
        // we set a small timeout to let the click / keypress event to trigger
        // and update our boolean
        setTimeout(focusHandler,100);
    });
    

    Whipped up a small working prototype on jsFiddle (don't you just love this site?). Check it out if you want.

    Of course, this is all running off a focus event on an , but the focus handler on the autocomplete works in the same way.

    The setTimeout will introduce a bit of lag, but at 100ms, it might be negligible, based on your needs.

提交回复
热议问题