jQuery 上下文菜单项仅单击文本

jQuery context menu item only clicked on text

单击上下文菜单中的项目时:

这里是jsFiddle。 (fiddle 似乎不起作用,尽管它在 Netbeans 中有效)。


var currentPopup = null;

$(function() {
  $('#idContainer').bind("contextmenu", function(e) {
    e.preventDefault();
    currentPopup = null;
    renderMenu({
      'Red': 'red',
      'Blue': 'blue',
      'Green': 'green'
    }, e.pageX, e.pageY);
  });

  $(document).bind("mousedown", function(e) {
    if (!$(e.target).parents(".contextMenu").length > 0) {
      closePopup();
    }
  });

}); // End of jQuery onLoad

function red(x, y) {
  $('#idContainer').css("background-color", "red");
}

function blue(x, y) {
  $('#idContainer').css("background-color", "blue");
}

function green(x, y) {
  $('#idContainer').css("background-color", "green");
}

// Render the context menu
function renderMenu(labelFunctionMap, x, y) {
  var html;
  html = '<ul class="contextMenu">';
  for (var label in labelFunctionMap) {
    html += '<li><a onclick="closePopup();' + labelFunctionMap[label] + '(' + x + ',' + y + ');">' + label + '</a></li>';
  }
  html += '</ul>';
  $("#idContainer").append(html);
  currentPopup = $(".contextMenu");
  currentPopup.css({
    top: y + "px",
    left: x + "px"
  });
  currentPopup.show();
}

// Close current context menu
function closePopup() {
  if (currentPopup != null) {
    currentPopup.hide(10);
    currentPopup.remove();
  }
  currentPopup = null;
}
#idContainer {
  position: static;
  height: 400px;
  width: 800px;
  border: 1px solid black;
}
.contextMenu {
  display: none;
  z-index: 1000;
  position: absolute;
  overflow: hidden;
  border: 1px solid #000;
  background: #FFF;
  white-space: nowrap;
  font-family: sans-serif;
  color: #333;
  border-radius: 5px;
  list-style-type: none;
  padding: 0;
  margin: 0;
}
.a {
  width: 100%
}
.contextMenu li {
  padding: 4px 8px;
  cursor: pointer;
}
.contextMenu li:hover {
  background-color: lightgrey;
}
<div id="idContainer"></div>

我认为您需要使您的 <a> 标签块级别,然后将 .contextMenu li 中的填充和其他 CSS 规则应用到您的 <a> 标签。然后可以删除 .contextMenu li 规则:

a {
    cursor: pointer;
    display: block;
    padding: 4px 8px;
}
a:hover {
    background-color: lightgrey;
}

已更新 jsFiddle:https://jsfiddle.net/sg09ec6r/5/