Differentiate between mouse and keyboard triggering onclick

前端 未结 7 1096
你的背包
你的背包 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 13:55

    I know this is an old question but given how much time I lost looking for a working, no jquery and IE-compatible solution, I think it won't be a bad idea to put it here (where I came first).

    I tested this and found it working fine :

    let mouseDown = false;
    
    element.addEventListener('mousedown', () => {
      mouseDown = true;
    });
    
    element.addEventListener('mouseup', () => {
      mouseDown = false;
    });
    
    element.addEventListener('focus', (event) => {
      if (mouseDown) {
        // keyboard
      } else {
        // mouse
      }
    });
    

    Source link : https://www.darrenlester.com/blog/focus-only-on-tab

提交回复
热议问题