尊敬的读者们,我在学习JavaScript时遇到了一个问题。我正试图实现这个修改版的力导向图:http://mbostock.github.com/d3/ex/force.html。JSON数据是通过PHP脚本动态生成的。我的想法是将与PHP脚本中定义的特定节点相连的所有线条都着为一种颜色,并将其他节点的线条着成灰色。我尝试通过匹配JSON文件中的源变量和PHP脚本中的变量,当它们相等时改变颜色,像这样:
然而,这并不起作用。如果我只是这样做,脚本可以正常工作,但没有颜色变化。
我已经盯着这个问题几天了,试图弄清楚如何完成它,但我卡住了。非常感谢任何帮助!
以下是我的完整脚本:
var link = svg.selectAll("line.link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value);})
.style("stroke-opacity", function(d) { return d.value/10;})
.style("stroke", function(d) {
x = (tested == d.source) ? return '#1f77b4' : '#707070';// <-- Attempt to change the color of the link when this is true.
})
然而,这并不起作用。如果我只是这样做,脚本可以正常工作,但没有颜色变化。
var link = svg.selectAll("line.link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value);})
.style("stroke-opacity", function(d) { return d.value/10;})
.style("stroke", function(d) {
return '#707070';
})
我已经盯着这个问题几天了,试图弄清楚如何完成它,但我卡住了。非常感谢任何帮助!
以下是我的完整脚本:
<script type="text/javascript">
var width = 1200,
height = 1200;
var color = d3.scale.category20();
var tested=<?php echo $tested_source;?>; //<-- the variable from php
var svg = d3.select("#chart").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("data.json", function(json) {
var force = d3.layout.force()
.charge(-130)
.linkDistance(function(d) { return 500-(50*d.value);})
.size([width, height]);
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll("line.link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value);})
.style("stroke-opacity", function(d) { return d.value/10;})
.style("stroke", function(d) {
x = (tested == d.source) ? return '#1f77b4' : '#707070'; //<-- Attempt to change the color of the link when this is true. But is is not working... :(
})
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 12)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.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; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
</script>
tested
进行测试。我认为问题就出在那里。 - Jérémie Parker.style("stroke", function(d) { console.dir(d.source); return (tested == d.source) ? '#1f77b4' : '#707070'; })
这段代码可以帮助你找到为什么颜色没有改变。请使用Firefox + Firebug或Chrome和Chrome开发者工具。我认为除此之外,我无法再帮助你了。 - Jérémie Parkerconsole.dir(d.source)
的结果。 - Jérémie Parkerd
,它是一个源。如果你想操作链接,那么使用this
,但我不知道你试图针对tested
进行什么测试,所以很难进行有意义的测试。你把tested = 20
,但应该等于 20 的是什么? - Jérémie Parker