保持已加载复选框的列表以进行多选



我遵循了一个解决方案"点击下拉菜单";,非常感谢@thisOneGuy。我可以通过左键单击<rect>区域来显示复选框列表。但我遇到了一个问题,每次我点击其中一个复选框时,整个列表都会消失。如果我想进行多选,我必须再次左键单击。

下面是代码。我删除了不必要的部分,只留下有用的部分来简化描述:

HTML:

<body>
<ul class='custom-menu'>
<li data-action="first"><input type="checkbox"> First thing</li>
<li data-action="second"><input type="checkbox">Second thing</li>
<li data-action="both"><input type="checkbox">Third thing</li>
</ul>
<div class="container">
<div class="row">
<svg id="svg2">
<g id="layer1">
...
<rect id="rect3643" style="stroke:#000000;stroke-width:.98070;fill:none" rx="4.5514" ry="3.1535" height="24.137" width="15.424" y="494.5" x="376.52" />
...
</g> 
</svg>
</div>
</div>
</body>

CSS:

.custom-menu {
display: none;
z-index: 1000;
position: absolute;
overflow: hidden;
border: 1px solid #CCC;
white-space: nowrap;
font-family: sans-serif;
background: #FFF;
color: #333;
border-radius: 5px;
}
.custom-menu li {
padding: 8px 12px;
cursor: pointer;
list-style-type: none;
}
.custom-menu li:hover {
background-color: #DEF;
}

Javascript:

$(document).ready(function(){
var rects = d3.selectAll("rect");
rects.on("click", function(event) {
// Avoid the real one
d3.event.preventDefault();

// Show contextmenu
$(".custom-menu").finish().toggle(100).

// In the right position (the mouse)
css({
top: d3.event.pageY + "px",
left: d3.event.pageX + "px"
});
});
// If the document is clicked somewhere
$(document).bind("mousedown", function(e) {
// If the clicked element is not the menu
if (!$(e.target).parents(".custom-menu").length > 0) {

// Hide it
$(".custom-menu").hide(100);
}
});
// If the menu element is clicked
$(".custom-menu li").click(function() {
// This is the triggered action name
switch ($(this).attr("data-action")) {

// A case for each action. Your actions here
case "first":
polygonClicked("first");
break;
case "second":
polygonClicked("second");
break;
case "both":
polygonClicked("first");
polygonClicked("second");
break;
}

// Hide it AFTER the action was triggered
$(".custom-menu").hide(100);
});
}); 

我在css上没有做太多更改,在JS中做了一些修改。函数polygonClicked(e)是我为改变其他多边形的背景而编写的函数。

有人能帮我让列表可以多选,并且只有当我点击列表区域外时才会消失吗?

您可以简单地从共享的代码中删除最后一行$(".custom-menu").hide(100);,只要单击列表项,就会隐藏菜单。

最新更新