2014-11-21 26 views
2

我有一个节点阵列。我希望单击一个HTML按钮并将所有这些节点的样式更改为该样式。我如何选择所有节点并将CSS样式应用于所有节点,D3

(例如:当我搜索一个节点或单击以选中,我要点击“清除”按钮,使一切复位)

肯定有一个简单的答案,但我似乎无法得到它上述

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

.node.unselectedNode { 
} 

是希望

回答

2

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

// 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); 
+0

由于某种原因,当我这样做时,底部的点击功能无法调用'unselectAllNodes? :/ 难道我做错了什么 ? – rekoDolph 2014-11-21 15:27:17

+0

我把一个控制台日志在该变量,以检查它是否已达到并没有什么来的​​ – rekoDolph 2014-11-21 15:28:46

+0

你已经宣布'unselectAllNodes ** **之前**使用它在'on'函数? – jleft 2014-11-21 15:29:42

-1

之间交替使用jQuery的CSS,你可以做到这一点。

$('mybutton').click(function(){ 
    $('myNodes').remoceClass('selectedNode').addClass('unselectedNode') 
}); 
+0

nope。不工作 – rekoDolph 2014-11-21 14:51:39

+0

这是你想要的吗? [http://jsfiddle.net/vpgpgkwz/](http://jsfiddle.net/vpgpgkwz/) – Alberto 2014-11-21 15:10:09

+0

正是我想要的谢谢,但你知道如何做到这一点不使用jQuery? – rekoDolph 2014-11-21 15:15:36

0

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

更多相关内容,你可以看到the example。这个特殊的例子使用svg.selectAll()来选择链接类的所有元素,这可能或可能不适用于你的情况。如果您需要更复杂的选择,则相关文档为here

作为替代,.attr方法支持使用函数根据所选节点的数据采取操作。您可以在the documentation

1

可以说你的节点是矩形找到更多的信息,你可以使用。对(“点击”),以

按钮上点击==> 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(); 
}); 
+0

这样做我如何选择所有节点并将CSS样式应用于它们? – rekoDolph 2014-11-21 15:04:04

+0

@AaronJones检查我的编辑 – 2014-11-21 15:05:04

相关问题