Differentiate between focus event triggered by keyboard/mouse

后端 未结 4 1450
有刺的猬
有刺的猬 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条回答
  •  Happy的楠姐
    2020-12-03 17:35

    The easiest and most elegant way I've found of achieving this is to use the "What Input?" library. It's tiny (~2K minified), and gives you access to the event type both in scripts:

    if (whatInput.ask() === 'mouse') {
      // do something
    }
    

    ...and also (via a single data attribute that it adds to the document body) styles:

    [data-whatinput="mouse"] :focus,
    [data-whatinput="touch"] :focus {
      // focus styles for mouse and touch only
    }
    

    I particularly like the fact that where you just want a different visual behaviour for mouse / keyboard it makes it possible to do that in the stylesheet (where it really belongs) rather than via some hacky bit of event-checking Javascript (though of course if you do need to do something that's not just purely visual, the former approach lets you handle it in Javascript instead).

提交回复
热议问题