gpt4 book ai didi

javascript - d3js 强制按钮允许/禁用拖动操作

转载 作者:行者123 更新时间:2023-11-29 14:48:08 27 4
gpt4 key购买 nike

我的目标是允许或禁用图表节点上的拖动操作。我有这个输入:<input id="drag" name="drag" type="button" value="switch drag" /> .我发现了一些提示 herethis question .

正如我在下面的评论中所说,如果我从外部 json 文件创建节点和链接,它就不起作用。是我的函数 d3.json("graph.json", function(error, graph) {...});不正确?

这是我的 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;
});

我希望有人能回答我,我的帖子可以帮助其他人!提前致谢!

最佳答案

对按钮使用 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;
});

http://jsfiddle.net/77yndu1e/2/

关于javascript - d3js 强制按钮允许/禁用拖动操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29962826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com