簡體   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