Safai / OSX上的contextmenu通过打开它的单击而关闭

时间:2018-11-08 22:27:00

标签: javascript contextmenu

我在框上有一个上下文菜单,例如适用于Windows上的Chrome和IE可以正常使用的“复制/剪切/粘贴”功能,但在Safari(OSX)上则不能。出现上下文菜单,但是一旦我放开mouseclicker(无论是否在窗口上方),它就会被隐藏,并且不会捕获其<li>上的任何单击。

我怀疑正在发生的情况是contextmenu事件的初始单击(控制单击是?)被传播到$(document),然后将其关闭。这是代码的相关部分。感谢您的帮助!

<select class="mySelectionsSelects"></select>
<select class="mySelectionsSelects"></select>

<ul id="custom-menu" style="top: 194px; left: 884px; display: none;">
  <li id="customMenuCopy" data-action="copy">Copy</li>
  <li id="customMenuCut" data-action="cut">Cut</li>
  <li id="customMenuPaste" data-action="paste">Paste</li>
</ul>

事件处理:

jQuery(document).ready(function ($) {
 $('.mySelectionsSelects').on("contextmenu", function(event) { 
   event.preventDefault(); event.stopPropagation();
   console.log('building context menu');
   $("#custom-menu").css({"top": event.pageY + "px", "left": event.pageX +    "px"});
   $("#custom-menu").show();
   console.log('added context menu at top: ' + event.pageY + '/left: ' +    event.pageX);
 });

// catch click anywhere else, to close it.
$(document).on("click", function(event) {
  console.log('caught click on document, hiding custom-menu');
  $("#custom-menu").hide();
});

$("#custom-menu li").on("click", function(event) {
  event.preventDefault(); event.stopPropagation();
  console.log('caught click in li'); 
  // This is the triggered action name
  switch($(this).attr("data-action")) {
    case "copy": editButton.doCopy(); break;
    case "cut": editButton.doCut(); break;
    case "paste": editButton.doPaste(); break;
  };
  // Hide it AFTER the action was triggered
  $("#custom-menu").hide(100);    
 });
});

css:

#custom-menu {
    display: none;
    z-index: 1000;
    position: absolute;
    overflow: hidden;
    border: 1px solid #CCC;
    white-space: nowrap;
    font-family: "Open Sans", sans-serif;
    font-size: 10pt;
    background: #FFF;
    color: #333;
    border-radius: 5px;
    padding: 0;
}

#custom-menu li {
    padding: 6px 9px;
    cursor: pointer;
    list-style-type: none;
    transition: all .3s ease;
    user-select: none;
}

#custom-menu li:hover {
  background-color: #DEF;
}

1 个答案:

答案 0 :(得分:1)

您的怀疑是正确的!在上下文菜单关闭功能的开头添加以下行:

if (event.ctrlKey) return;

资料来源:https://stackoverflow.com/a/27973894/7503963(我没有代表仅作评论。)