繁体   English   中英

我如何选择所有节点并将CSS样式应用于所有节点D3

[英]How do i select all nodes and apply a css style to all of them, D3

我有一个节点数组。 我希望单击一个HTML按钮,并将所有这些节点的样式更改为该样式。

(例如:当我搜索节点或单击以进行选择时,我想单击“清除”按钮,以便重置所有内容)

当然有一个简单的答案,但我似乎无法理解

.node.selectedNode {
    width:50px;
    height:50px;
    stroke-width: 3px;
    stroke: #f00;
}

.node.unselectedNode {  
}

上面是我希望在其中替换的CSS

要添加或删除CSS类,可以使用选择。 分类功能:

// Select all elements with the node class
d3.selectAll(".node")  
    .classed("selectedNode", true) // Add the selectedNode class to the selection
    .classed("unselectedNode", false); // Remove the unselectedNode class to the selection

选择。 on功能可用于侦听按钮的单击,例如,清除按钮功能(如果您具有以下按钮):

<button id="reset">Clear</button>

然后可以适当地设置分类:

var unselectAllNodes = function () {
    d3.selectAll(".node")
        .classed("selectedNode", false)
        .classed("unselectedNode", true);
};

// Call the unselectAllNodes function when this button is clicked
d3.select("button#reset")
    .on('click', unselectAllNodes);

假设您的节点是rect,您可以使用.on('click')

单击按钮==> set_variable范围更高==>调用D3函数重新渲染

var set_variable;
$('#button').on('click', function () {
  if(something) {set_variable="classA";}
  else {set_variable="classB";}

  D3Function();
});

D3Function ==> ...

canvas.selectAll("rect").data(scope.input).enter()
  .append("rect").call(yAxis)

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

  .on("click", function(d, i){ 
  //d is the document, i the index
   });

....

$('#reset').on('click', function () {
  set_variable="";     
  D3Function();
});

您可以使用以下代码向节点添加类: .attr("class", "link")

有关更多上下文,请参见示例 这个特定的示例使用svg.selectAll()选择具有链接类的所有元素,这在您的情况下可能有效,也可能无效。 如果您需要更复杂的选择,相关文件是在这里

作为替代, .attr方法支持使用函数根据选定节点的数据采取措施。 您可以在文档中找到更多信息

暂无
暂无

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

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