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

时间:2015-05-20 08:51:20

标签: jquery css contextmenu

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

  • 仅在直接单击文本时才有效。
  • 如果单击文本旁边的空白区域,它也可以正常工作。

这是jsFiddle。 (尽管它在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;
}
&#13;
#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;
}
&#13;
<div id="idContainer"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我认为您需要设置<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/