JS: detect right click without jQuery (inline)

后端 未结 2 1406
轻奢々
轻奢々 2020-12-15 01:10

I\'m calling a function, that builds a table which includes several links.

I want to check if a link has been clicked with right or left mouse.

I tried to ad

相关标签:
2条回答
  • 2020-12-15 01:43

    Here's a modification of xdazz's answer that supports browsers that use e.button, normalizes the value, and stores it in e.which. The added lines are what are used in the JQuery library.

    function mouseDown(e) {
      e = e || window.event;
      if ( !e.which && e.button !== undefined ) {
        e.which = ( e.button & 1 ? 1 : ( e.button & 2 ? 3 : ( e.button & 4 ? 2 : 0 ) ) );
      }
      switch (e.which) {
        case 1: alert('left'); break;
        case 2: alert('middle'); break;
        case 3: alert('right'); break; 
      }
    }​
    
    0 讨论(0)
  • 2020-12-15 01:55

    The html:

    <a href="#" onmousedown="mouseDown(event);">aaa</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    The javascript:

    function mouseDown(e) {
      e = e || window.event;
      switch (e.which) {
        case 1: alert('left'); break;
        case 2: alert('middle'); break;
        case 3: alert('right'); break; 
      }
    }​
    

    The demo.

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