我仍在我的图表上,我需要默认关闭2级和3级节点,并在点击时保持展开/折叠功能.
根据单击的节点及其级别,运行特定操作(例如更改颜色).我的链接必须是我的数据对象的值(我的codepen中的var pubs),你可以看到如下(级别0没有链接,在我的例子中是"TOOLS"):
{
"name": "TOOLS",
"children":
[
{
"name": "Localization",
"url": "http://#",
"children":
[
{"name": "FRANCE", "url": "http://france.fr"}
...
Run Code Online (Sandbox Code Playgroud)
最后一个关于"鼠标悬停"的事件监听器在节点上做一些样式(关闭或打开)等...
如果要折叠除根节点和第一组子节点之外的所有节点,可以运行以下代码:
\n\nroot.children.forEach(collapse);\nRun Code Online (Sandbox Code Playgroud)\n\n这会递归地将collapse函数应用于根的所有子节点。
您的节点上已经有一个点击事件监听器,您可以根据您的计划进行更改。添加 mouseover 和 mouseout 事件的监听器非常简单:
\n\nvar nodeEnter = node.enter().append("g")\n.attr("class", "node")\n.on("click", click)\n.on(\'mouseover\', mouseover) // mouseover!\n.on(\'mouseout\', mouseout) // mouseout!\nRun Code Online (Sandbox Code Playgroud)\n\n然后,您需要添加函数来定义发生的操作。以下是几个示例函数:
\n\n// `d` is the data item attached to the DOM node;\n// `this` is the node that triggered the event (`g.node`)\nfunction mouseover(d) {\n // select the `rect` node that is the child of the DOM node that triggered the event\n d3.select(this).select(\'rect\').style(\'fill\', function(d){\n // depending on the level of the node, give it one of these tacky colours\n if (d.depth === 0) {\n return \'deepskyblue\'\n } else if (d.depth === 1) {\n return \'deeppink\'\n } else if (d.depth === 2) {\n return \'goldenrod\'\n }\n return \'papayawhip\' // default\n })\n}\n\nfunction mouseout(d) {\n // select the rect element\n d3.select(this).select(\'rect\')\n // if the node has collapsed children, turn it light blue; otherwise turn it red\n .style(\'fill\', d => d._children ? "lightsteelblue" : "red")\n}\nRun Code Online (Sandbox Code Playgroud)\n\nclick您还可以以类似的方式向该函数添加额外的功能。
以下是正在运行的事件侦听器:
\n\nroot.children.forEach(collapse);\nRun Code Online (Sandbox Code Playgroud)\r\nvar nodeEnter = node.enter().append("g")\n.attr("class", "node")\n.on("click", click)\n.on(\'mouseover\', mouseover) // mouseover!\n.on(\'mouseout\', mouseout) // mouseout!\nRun Code Online (Sandbox Code Playgroud)\r\n// `d` is the data item attached to the DOM node;\n// `this` is the node that triggered the event (`g.node`)\nfunction mouseover(d) {\n // select the `rect` node that is the child of the DOM node that triggered the event\n d3.select(this).select(\'rect\').style(\'fill\', function(d){\n // depending on the level of the node, give it one of these tacky colours\n if (d.depth === 0) {\n return \'deepskyblue\'\n } else if (d.depth === 1) {\n return \'deeppink\'\n } else if (d.depth === 2) {\n return \'goldenrod\'\n }\n return \'papayawhip\' // default\n })\n}\n\nfunction mouseout(d) {\n // select the rect element\n d3.select(this).select(\'rect\')\n // if the node has collapsed children, turn it light blue; otherwise turn it red\n .style(\'fill\', d => d._children ? "lightsteelblue" : "red")\n}\nRun Code Online (Sandbox Code Playgroud)\r\n| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |