Javascript 检测上下文菜单何时关闭

Javascript detecting when contextmenu is closed

我有两个 canvas 堆叠在一起

<div id="canvases" class="col-lg-11">
      <canvas id="canvas"  style="z-index: 1;"></canvas>
      <canvas id="canvas2" style="z-index: 3;"></canvas>
</div>

当用户尝试保存图片时,我希望#canvas 位于顶部以便保存。

$("#canvases").on('mousedown', function (e) {
  if (e.which === 3){ //right click
    canvas.style.zIndex = "4";
    return;
  }

但是,我需要它在上下文菜单关闭时返回。

上下文菜单关闭时是否有事件,或者更有效的保存方式#canvas?


注意:2012年有过类似的问题,但我认为这个问题没有得到完整的回答。

Is there a close event for the browser contextmenu

答案间接检测上下文菜单是否关闭(通过检查点击),但不检查菜单选项何时被选中。

我猜这是因为没有直接的方法来检测上下文菜单的关闭,但想知道它是否可能从那时起就出现了。

afaik 仍然无法检测到这一点,但可能有另一种方法可以解决您的问题,而无需知道这一点。

如果这是一个选项,您可以在顶部的元素上使用 pointer-event: none,这样鼠标事件将忽略顶层,但这可能会对您的代码产生另一个副作用。

.container {
  position: relative;
  left: 0px;
  top: 0px;
  width: 350px;
  height: 150px;
}

.ontop {
  position: absolute;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 2;
  background-color: rgba(0, 0, 0, 0.5);
  pointer-events: none;
}
<div class="container">
  <img src="http://placehold.it/350x150">
  <div class="ontop">
  </div>
</div>

另一件事你可以做但我不确定它是否跨浏览器工作是在捕获阶段更改 mousedown 上的 z-index 并在几毫秒后重置它,这样该事件仍然针对您向上移动的元素。

document.addEventListener('mousedown', function(e) {
  if (e.which === 3) {
    $('.ontop').css({
      zIndex: -1
    });
    setTimeout(function() {
      $('.ontop').css({
        zIndex: ''
      });
    }, 10);
  }
}, true);
.container {
  position: relative;
  left: 0px;
  top: 0px;
  width: 350px;
  height: 150px;
}

.ontop {
  position: absolute;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 2;
  background-color: rgba(0, 0, 0, 0.5);
}
<script   src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div class="container">
  <img src="http://placehold.it/350x150">
  <div class="ontop">
  </div>
</div>