我的目标是允许或禁用图表节点上的拖动操作。我有这个输入:<input id="drag" name="drag" type="button" value="switch drag" />
。我在here找到了一些提示this question。
正如我在下面的评论中所说,如果我从外部json文件创建节点和链接,它将不起作用。我的函数是d3.json(“graph.json”,函数(错误,图形){...});不正确吗?
这是我的json文件:
{
"nodes": [
{"x": 260, "y": 210, "fixed": true},
{"x": 300, "y": 210, "fixed": true},
{"x": 260, "y": 260, "fixed": true},
{"x": 300, "y": 260, "fixed": true}
],
"links": [
{"source": 0, "target": 1},
{"source": 0, "target": 2},
{"source": 2, "target": 3},
{"source": 3, "target": 1}
]
}
这是我的代码:
var width = 960, height = 500;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var myLinks = svg.selectAll(".link");
var myNodes = svg.selectAll(".node");
var force = d3.layout.force()
.size([width, height])
.charge(-400)
.linkDistance(40)
.on("tick", tick);
// Allows the drag actions
var drag = force.drag();
// Read the json file and creates the links and the nodes
d3.json("graph.json", function(error, graph) {
if (error) alert(error);
force
.nodes(graph.nodes)
.links(graph.links)
.start();
myLinks = myLinks.data(graph.links)
.enter()
.append("line")
.attr("class", "link");
myNodes = myNodes.data(graph.nodes)
.enter()
.append("circle")
.attr("class", "node")
.attr("r", 6)
.call(drag);
});
// Add properties to myLinks and myNodes
function tick() {
myLinks.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
myNodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
var dragOnOff = d3.select("#drag");
dragOnOff.on("click", function() {
myNodes.on('mousedown.drag', null);
});
var dragOnOff = d3.select("#drag");
var dragCallback = myNodes.property('__onmousedown.drag')['_'];
var draggable = true;
dragOnOff.on("click", function () {
myNodes.on('mousedown.drag', draggable ? null : dragCallback);
this.value = 'switch drag to ' + draggable;
draggable = !draggable;
});
我希望有人能回答我,我的帖子可以帮助别人! 提前谢谢!
答案 0 :(得分:2)
使用on "click"
代替on "input"
按钮。
var dragOnOff = d3.select('#drag');
var draggable = true;
dragOnOff.on('click', function () {
myNodes.on('mousedown.drag', draggable ? null : dragCallback);
draggable = !draggable;
});