Differentiate between focus event triggered by keyboard/mouse

后端 未结 4 1453
有刺的猬
有刺的猬 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条回答
  •  故里飘歌
    2020-12-03 17:43

    The first thing that comes to mind is that you can find the position of the mouse and check to see if its within the position of the element

    Use this to store the position of the element:

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

    Then use this to find absolute position of the mouse within the window:

    var cur_mx, cur_my;
    $(document).mousemove(function(e){
       cur_mx = e.pageX;
       cur_my = e.pageY;
    });
    

    Then in your autcomplete setup:

    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!
       }
    }
    

提交回复
热议问题