Это ссылка для jsfiddle. Это не отображается как в моем коде, но то, что я создал, отлично работает на моем конце, но не может реплицироваться на jsfiddle. Я хочу, чтобы статус ребенка был красным или проблемным. цвет родителя должен быть красным до тех пор, пока мы не откроем его ребенку, у которого возникнет проблемаD3/изменить цвет родителя, если дочерний статус красного цвета или номер
как если бы «проверка 9» возникла проблема, чем «Тест» должен быть красным с текстом и красным узлом, когда он нажимает на него, он должен вернуться к нормальному, а следующее, которое проверяется 1, должно быть красным, если открыто, чем проверка 2 и так далее, пока я не дойду до проблемного ребенка, который проверяет 9 для демонстрации.
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = window.innerWidth - margin.right - margin.left - 20,
height = window.innerHeight - margin.top - margin.bottom - 120;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.call(d3.behavior.zoom().scaleExtent([0.5, 2]).on("zoom", function() {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")")}))
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var flare = {
"name": "Test",
"children": [
{
"name": "head 1",
"children": [
{
"name": "head 2",
"children": [
{
"name": "head 3",
"children": [
{
"name": "head 4",
"children": [
{
"name": "head 5",
"children": [
{
"name": "head 6",
"children": [
{
"name": "head 7",
"children": [
{
"name": "head 8",
"children": [
{
"name": "head 9",
"children": [
{"name": "gi"},
{"name": "hi"}
]
}
]
}
]
}
]
}
]
}
]
},
{
"name": "head1",
"children": [
{
"name": "head 2",
"children": [
{
"name": "head 3",
"children": [
{
"name": "head 4",
"children": [
{
"name": "head 5",
"children": [
{
"name": "head 6",
"children": [
{"name": "hi"},
{"name": "hi"}
]
}
]
}
]
}
]
}
]
}
]
},
{
"name": "head 1",
"children": [
{
"name": "head 2",
"children": [
{
"name": "head 3",
"children": [
{
"name": "head 4",
"children": [
{
"name": "head 5",
"children": [
{
"name": "head 6",
"children": [
{"name": "hi"},
{"name": "hi"}
]
},
{
"name": "R",
"children": [
{"name": "hi"},
{"name": "hi"}
]
},
{
"name": "rr",
"children": [
{"name": "hi"},
{"name": "hi"}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
},
{
"name": "check 1",
"children": [
{
"name": "check 2",
"status":"red",
"children": [
{
"name": "check 3",
"children": [
{
"name": "check 4",
"children": [
{
"name": "check 5",
"children": [
{
"name": "check 6",
"children": [
{
"name": "check 7",
"children": [
{
"name": "check 8",
"children": [
{
"name": "check 9",
"status":"red",
"children": [
{"name": "problem","url":"www.google.com"},
{"name": "hi","url":"www.google.com"}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
};
//if (error) throw error;
root = flare;
root.x0 = height/2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
d3.select(self.frameElement).style("height", "800px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on('contextmenu',d3.contextMenu(content))
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? (d.status ? d.status : "#f77a03") : "#fff"; });//changed
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", function(d) { return d.children || d._children ? -10 : 10; })
.style('fill',function(d) { return d.status ? d.status : "white"; })//added
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? (d.status ? d.status : "#f77a03") : "#fff"; });//changed
nodeUpdate.select("text")
.style('fill',function(d) { return d.status ? d.status : "black"; })//added
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
//expand and collapse
function expand(d){
var children = (d.children)?d.children:d._children;
if (d._children) {
d.children = d._children;
d._children = null;
}
if(children)
children.forEach(expand);
}
function expandAll(){
expand(root);
update(root);
}
function collapseAll(){
root.children.forEach(collapse);
collapse(root);
update(root);
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
//on right click
var content = [
{
title: 'Item #1',
action: function(elm, d, i) {
window.open(d.url, '_blank');
}
},
{
title: 'Item #2',
action: function(elm, d, i) {
window.open(d.url, '_blank');
}
}
]
Не хотите узел, чтобы изменить его расположение
Пусть это часть JSON, узел «проверить 9» оказывает статус «красный». Но когда мы загружаем страницу, мы не можем ее увидеть, пока мы не разберем все или не достигнем этой точки. Поэтому я хочу, чтобы цвет корневого узла был красным при загрузке страницы, поэтому я буду знать, что там есть какая-то проблема (некоторый узел имеет статус красного цвета). тогда, когда я нажму на корневой узел или появится более детальный дочерний узел, в этом случае «Проверка 2» будет красной на загрузке страницы, и когда я нажму на нее, так как она не имеет собственного статуса, она изменится на цвет по умолчанию и «check 3» изменится на красный и так далее, пока не достигнет «check 9», который останется красным, так как он красный. Это нужно делать только в том случае, если статус красного цвета не в любом другом случае. Если до сих пор не ясно, чем я на самом деле нужно, чтобы присоединиться приговор комплектовать классы :(
"name": "check 1",
"children": [
{
"name": "check 2",
"children": [
{
"name": "check 3",
"children": [
{
"name": "check 9",
"status":"red",
"children": [
{"name": "problem","url":"www.google.com"},
{"name": "hi","url":"www.google.com"}
]
}
]
}
]
}
]
Также вторая часть вашего вопроса трудно понять, не могли бы вы уточнить? – thatOneGuy
думаю, что 'd.children [i] .status = 'red'' должно быть 'd.children [i] .status == 'red'' право? – Cyril
@ Кирилл хорошее место, как уже упоминалось, это не тестирование, спасибо за это, отредактирован ответ :) – thatOneGuy