【发布时间】:2018-06-15 15:08:31
【问题描述】:
如何使用鼠标右键和 CRTL 键选择多个 SVG 元素?
我想要的类似于我找到的this example(右侧部分)。 可以只选择一个元素,也可以按住 CTRL 键选择多个元素。
我查看了代码,但在我的情况下无法重现它。
我的情况: JSFIDDLE
我希望可以选择更多圈子。
我希望当用户选择一个圆圈时,打印所选圆圈的id。
当用户完成选择他想要的内容并按下Finish 按钮时,我希望打印所选项目的列表。
这可以吗?非常感谢任何帮助。
更新
我更改了@Shashank 的代码,现在它可以工作了。我希望它对某人有用:)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="style.css" media="screen"/>
</head>
<body>
<div id="circles">
<svg>
<circle id="first" cx="10" cy="10" r="10" fill="purple" />
<circle id="second" cx="60" cy="60" r="5" fill="red" />
<circle id="third" cx="110" cy="110" r="15" fill="orange" />
<circle id="fourth" cx="90" cy="50" r="7" fill="yellow" />
</svg>
</div>
<button type="button" id="finalSelection">Finish</button>
<span style="display:block;margin-top: 10px;">Selected IDs: <span class="values"></span></span>
<script src="script.js"></script>
</body>
</html>
script.js
var selectedIds = [];
d3.selectAll('#circles svg circle').on('click', function() {
// fetch ID
var id = d3.select(this).attr('id');
// toggle "clicked" class and push/splice id within the selectedIds array accordingly based on event.metaKey (CTRL)
if(d3.select(this).classed('clicked')) { // classed add/remove a CSS class from the selection
d3.select(this).classed('clicked', false).style('stroke', null);
selectedIds.splice(selectedIds.indexOf(id), 1); // the splice() method adds/removes items to/from an array, and returns the removed item(s)
}
else { // if an item has never been selected
if(selectedIds.length) { // if the array selectedIds is not empty
if(d3.event.ctrlKey) { // if CTRL is pressed
d3.select(this).classed('clicked', true).style('stroke', 'blue');
selectedIds.push(id);
}
else { // *** OK *** if the item I'm selecting has never been selected and before I had already selected other elements
// I "remove" all those already selected
d3.selectAll(".clicked").classed('clicked', false).style('stroke', null);
selectedIds = [];
// I consider selected the one actually selected
d3.select(this).classed('clicked', true).style('stroke', 'blue');
selectedIds.push(id);
}
}
else { // if the array selectedIds is empty
d3.select(this).classed('clicked', true).style('stroke', 'blue');
selectedIds.push(id);
}
}
$('span.values').html(selectedIds.join(', '));
});
$('button#finalSelection').click(function() {
$('span.values').html(selectedIds.join(', '));
console.log("compare!")
});
style.css
span.values {
color: #428bca;
}
JSFIDDLE 更新代码。
【问题讨论】:
标签: javascript d3.js svg selection multipleselection