給尊敬的讀者。我相當新的JavaScript,我遇到了這個問題。我想實現這個力有向圖的修改版本:從PHP腳本動態生成設置D3力向圖
http://mbostock.github.com/d3/ex/force.html
JSON數據。這個想法是用一種顏色將所有連接到一個特定節點(在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>
謝謝!當談到JavaScript時,我是一個完整的菜鳥。該建議確實可以使腳本正常工作,但它仍不會改變連接線的顏色。我認爲從json數組中檢索d.source可能會有問題。幫幫我?? – user1378824
我已經編輯了一些關於你正在測試的源代碼對象的代碼。我認爲問題來自那裏。 –
感謝您的快速回復。也許我誤解了一些東西,但是你指的對象是節點。我試圖改變節點之間連線的顏色。該值在miserables.json文件的「鏈接」中定義。我完全誤解了一些東西嗎? – user1378824