如何才能使右键单击以下功能?

时间:2018-05-04 08:21:22

标签: javascript

canvas.addEventListener("mousedown", getPosition, false);

      function getPosition(event)
      {
        var x = event.x;
        var y = event.y;

        var canvas = document.getElementById("canvas");

        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;

        alert("x:" + x + " y:" + y);
      }

这个简单的函数将为我提供鼠标点击位置的坐标,它目前可以左右点击,但我只想让它工作,如果它是右击,某种if rightClicked:

2 个答案:

答案 0 :(得分:3)

使用contextmenu事件:

canvas.addEventListener("contextmenu", getPosition, false);


function getPosition(event) {
  event.preventDefault();
  var x = event.x;
  var y = event.y;

  var canvas = document.getElementById("canvas");

  x -= canvas.offsetLeft;
  y -= canvas.offsetTop;

  console.log("x:" + x + " y:" + y);
  alert("x:" + x + " y:" + y);
}
canvas {
  background: red;
}
<canvas id="canvas"></canvas>

答案 1 :(得分:1)

浏览器将“右键单击”解释为“上下文菜单”。因此,您的事件处理程序需要绑定到$query->join('tbl_lawyer_cooperation', function ($s) use ($request) { $s->on('tbl_lawyer_cooperation.fk_lawyer_id', '=', 'vw_lawyers.lawyer_id') ->where(function ($d) use ($request) { $d->select('count') ->whereIn('tbl_lawyer_cooperation.fk_cooperation_id', $request->cooprations); },'>=',count($request->cooprations)); }); 事件。

尝试: contextmenu

canvas.addEventListener("contextmenu", getPosition, false);
canvas.addEventListener("contextmenu", getPosition, false);

function getPosition(event){
  var x = event.x;
  var y = event.y;

  var canvas = document.getElementById("canvas");

  x -= canvas.offsetLeft;
  y -= canvas.offsetTop;

  alert("x:" + x + " y:" + y);
}
canvas {
  background: green;
}