区分键盘/鼠标触发的焦点事件 [英] Differentiate between focus event triggered by keyboard/mouse

查看:197
本文介绍了区分键盘/鼠标触发的焦点事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery ui自动完成,并希望在键盘交互和鼠标交互触发的焦点事件之间进行解密。我该怎么做?

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?

$('input').autocomplete({
    source: function(request, response) {
        ...
    },
    focus: function(event, ui) {
        // If focus triggered by keyboard interaction
            alert('do something');
        // If focus event triggered by mouse interaction
            alert('do something else');
    }
});

谢谢

推荐答案

我能想到这样做的唯一方法是让一个处理程序监听 keypress 点击事件,并打开/关闭布尔标志。然后在你的输入的焦点处理程序中,你可以检查你的旗帜的价值,并从那里开始。

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.

可能类似于

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

在jsFiddle上制作一个小型工作原型(难道你不喜欢这个网站吗?)。 如果需要,请查看。

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

当然,这都是在< input> 上的焦点事件中运行,但是<$自动完成的c $ c> focus 处理程序以相同的方式工作。

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

setTimeout 会引入一些延迟,但在100毫秒时,根据您的需要可能会忽略不计。

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

这篇关于区分键盘/鼠标触发的焦点事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆