简体   繁体   English

d3.js树形布局如何使用函数命名类

[英]d3.js tree layout how to name classes using a function

I want to make a tree where the same thing can be listed multiple times, and on mouseover all of the same thing will expand or light up or something. 我想制作一棵树,在其中可以多次列出相同的事物,并且将鼠标悬停在同一棵树上时,所有相同的事物都会扩展或点亮。 What I can't figure out is how to do this. 我不知道该怎么做。 My initial thought was to use a line like 我最初的想法是使用类似

.attr("class", function(d){return d})

but that didn't seem to work. 但这似乎不起作用。 If anybody has any ideas about how to do this it would be much appreciated. 如果有人对如何执行此操作有任何想法,将不胜感激。 The tree for example may look like 例如树可能看起来像

Food
  Vegtables
    Carrot
    Pizza
  Tastes good
    Cake
    Pizza

I would want to be able to make it so that if i hover over pizza once in my tree both of them will do the same on mouseover action. 我希望能够做到这一点,以便如果我将悬停在树上的比萨饼上一次,它们在鼠标悬停动作上都将做同样的事情。

Most likely your code didn't work because d is an object (representing a node in the tree), and the default to-string behavior for objects returns "[object Object]"; 您的代码很可能无法正常工作,因为d是一个对象(表示树中的一个节点),并且对象的默认字符串行为返回“ [object Object]”; setting the class attribute to "[object Object]" won't help you select nodes by class. 将class属性设置为“ [object Object]”将无法帮助您按类选择节点。

You need to define the class attribute as a property of data . 您需要将class属性定义为data的属性 For example, if you data has a type property, then you could define the class attribute as 例如,如果数据具有type属性,则可以将class属性定义为

.attr("class", function(d) { return "node " + d.type; })

Next, register a mouseover and mouseout handler for interaction: 接下来,注册一个mouseover和mouseout处理程序以进行交互:

.on("mouseover", function(d) { highlight(d.type); })
.on("mouseout", function(d) { highlight(null); })

Finally, the highlight function selects nodes by class and toggles an active class which overrides the fill color. 最后,高亮功能按类选择节点,并切换覆盖填充颜色的活动类。

function highlight(type) {
  if (type == null) d3.selectAll(".node").classed("active", false);
  else d3.selectAll(".node." + type).classed("active", true);
}

The active class is defined as: 活动类定义为:

.node.active {
  fill: red;
}

Live example here: 现场示例:

For more details on how to select related nodes, see my answer to how do you select (and then modify) related elements? 有关如何选择相关节点的更多详细信息,请参见我关于如何选择(然后修改)相关元素的答案

Your answer is simple. 您的答案很简单。 Firstly, you will need to have access to the root of your tree? 首先,您将需要访问树的根? Got it? 得到它了? Good. 好。 Now you will just call jQuery on it to find what you are looking for and then toggle a class. 现在,您只需在其上调用jQuery即可查找所需内容,然后切换一个类。 Example: 例:

 $(root).find("pizza").hover(function(){
    $(this).toggleClass("colorChange");
 });

this is untested but if build correctly, would work 这未经测试,但如果构建正确,将可以工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM