区分键盘/鼠标触发的焦点事件

| 我正在使用jquery ui自动完成功能,并希望解释键盘交互和鼠标交互触发的焦点事件。我将如何处理?
$(\'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
click
事件,并打开/关闭布尔标志。然后,在输入的“ 3”处理程序上,您只需检查标志的值,然后从那里去即可。 大概像
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上制作了一个小的工作原型(您不只是喜欢这个网站吗?)。如果需要,请检查一下。 当然,这都是在
<input>
上的
focus
事件中发生的,但是自动完成中的
focus
处理程序的工作方式相同。
setTimeout
会带来一些滞后,但是根据您的需要,在100ms时,它可以忽略不计。     
您实际上应该能够从传递给焦点事件的事件对象中确定这一点。根据您的代码结构,这可能有所不同,但是通常在其中有一个称为
originalEvent
的属性,该属性可能嵌套了一定深度。仔细检查“ 10”对象,以确定正确的语法。然后通过正则表达式测试ѭ11或
keydown
。像这样:
focus: function(event, ui){
  if(/^key/.test(event.originalEvent.originalEvent.type)){
    //code for keydown
  }else{
    //code for mouseenter and any other event
  }
}
    
我找到的最简单,最优雅的方法是使用\“ What Input?\”库。它很小(最小约2K),可让您在脚本中访问事件类型:
if (whatInput.ask() === \'mouse\') {
  // do something
}
...以及(通过添加到文档“ 15”中的单个数据属性)样式:
[data-whatinput=\"mouse\"] :focus,
[data-whatinput=\"touch\"] :focus {
  // focus styles for mouse and touch only
}
我特别喜欢这样一个事实,即您只希望鼠标/键盘具有不同的视觉行为,就可以在样式表(它真正属于的地方)中做到这一点,而不是通过一些棘手的事件检查Javascript(当然,如果您确实需要做一些不只是视觉上的事情,前一种方法可以让您使用Javascript处理它)。     
首先想到的是,您可以找到鼠标的位置并检查它是否在元素的位置内 使用它来存储元素的位置:
var input = $(\'#your_autocompleted_element_id\'),
    offset = input.offset(),
    input_x = offset.top,
    input_y = offset.left,
    input_w = input.outerWidth(),
    input_h = input.outerHeight();
然后使用它来查找鼠标在窗口中的绝对位置:
var cur_mx, cur_my;
$(document).mousemove(function(e){
   cur_mx = e.pageX;
   cur_my = e.pageY;
});
然后在您的自动完成设置中:
focus: function(event, ui) {
   // mouse is doing the focus when...
   // mouse x is greater than input x and less than input x + input width
   // and y is greater than input y and less than input y + input height
   if (cur_mx >= input_x && cur_mx <= input_x + input_w && cur_my >= input_y && cur_my <= input_y + input_h) {
      // do your silly mouse focus witchcraft here
   } else {
      // keyboard time!
   }
}
    

要回复问题请先登录注册