我试图在d3强制布局中的节点上写一个点击,切换功能,并且没有什么可以帮助我弄清楚如何使其工作。我们的想法是,当您点击一个节点时,屏幕左侧会显示一个svg,当您再次单击时,它会消失。以下是我没有运气的代码:
var MainPage = React.createClass({
getInitialState: function() {
return {
value: 1
};
},

这里是完整代码的链接:http://plnkr.co/edit/nwmUN4RzAwam9dE5bCEj?p=preview
答案 0 :(得分:1)
这是你如何做到的。首先制作一个工具提示组。
var tooltip = svg.append("g").attr("transform", "translate(-300,0)");
//add rectangle to the group
tooltip.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 300)
.attr("height", height)
.attr("color", "black")
.attr("opacity", 0.8);
在节点上单击
var node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", function(d) {
if (tooltip.data && d.name == tooltip.data.name) {
//if clicked on the same node again close
tooltip.classed("open", false);
tooltip
.transition()
.attr("transform", "translate(-300,0)")//slide via translate
.duration(1000);
tooltip.data = undefined;//set the data to be undefined since the tooltip is closed
return;
}
tooltip.data = d;//set the data to the opened node
tooltip.classed("open", true);//set the class as open since the tooltip is opened
tooltip
.transition()
.attr("transform", "translate(0,0)")
.duration(1000);
d3.selectAll(".text-tip").remove(); //remove old text
tooltip.append("text")//set the value to the text
.attr("transform", "translate(10,100)")
.attr("class","text-tip").text(d.name);
})
工作示例here。
答案 1 :(得分:0)
只需添加:
需要定义:
var COLLAPSE_LEVEL = 1
并使用以下代码:
function toggleAll(d) {
if (d.children) {
d.children.forEach(toggleAll);
if (d.level < COLLAPSE_LEVEL) {
return;
}
toggle(d);
}
}
function toggle(d) {
if (d.children) {
d._children = d.children;
d.children= null;
} else {
d.children= d._children;
d._children = null;
}
}