JS:没有jQuery检测右键单击(内联)

时间:2012-02-29 14:19:11

标签: javascript right-click mousedown

我正在调用一个函数,它构建一个包含多个链接的表。

我想检查是否用鼠标左键单击了一个链接。

我尝试将以下部分添加到<a>超链接。

onmousedown="function mouseDown(e){
switch (e.which) {
   case 1: alert('left'); break;
   case 2: alert('middle'); break;
   case 3: alert('right'); break; }
}"

但没有任何反应如果我点击一个链接。

2 个答案:

答案 0 :(得分:15)

html:

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

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; 
  }
}​

demo

答案 1 :(得分:4)

这是对xdazz答案的修改,它支持使用e.button的浏览器,对值进行规范化,并将其存储在e.which中。添加的行是JQuery库中使用的。

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; 
  }
}​