Differentiate between mouse and keyboard triggering onclick

前端 未结 7 915
你的背包
你的背包 2020-12-03 13:09

I need to find a way to determine if a link has been activated via a mouse click or a keypress.



        
相关标签:
7条回答
  • 2020-12-03 14:09

    Could check if event.screenX and event.screenY are zero.

    $('a#foo').click(function(evt) {
      if (evt.screenX == 0 && evt.screenY == 0) {
        window.alert('Keyboard click.');
      } else {
        window.alert('Mouse click.');
      }
    });
    

    Demo on CodePen

    I couldn't find a guarantee that it works in all browsers and all cases, but it has the benefit of not trying to detect a "click" done via the keyboard. So this solution detects "click" more reliably at the cost of detecting if it's from keyboard or mouse somewhat less reliably. If you prefer the reverse, look as the answer from @Gonzalo.

    Note: One place I found using this method is Chromium

    0 讨论(0)
提交回复
热议问题