2016-08-18 50 views
1

我学习D3,到目前为止,我有一个基本的应用程序,显示美国地图,当用户将鼠标移动到一个状态时,它增加了文字识别元素。我想要做的也是在被挖空之后,国家变成另一种颜色。我至今:D3 - 通过数据

var svg = d3.select("body") 
    .append("svg") 
    .attr("width", 500) 
    .attr("height", 500); 

d3.json("/HelloWorld/data/states.json", function(data) { 
    var projection = d3.geo.albersUsa().translate([250,250]).scale(650); 
    var path = d3.geo.path().projection(projection); 
    svg.selectAll("path") 
    .data(data.features) 
    .enter() 
    .append("path") 
     .attr("d",path) 
     .attr("fill", "red") 
     .attr("stroke", "blue") 
     .on("mouseover", function(d, i) { 

    d3.select("body").append("text").html("</br>"+d.properties.NAME); 
}); 

的问题是,虽然我可以参照的数据与d,我需要能够参考的路径对象,以改变填充属性,我不确定如何从数据中获取实际的SVG元素。

+0

检查:http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922 –

+0

的'this'关键字是指数据元素被鼠标滑过。 – Mark

回答

0

this关键字是指数据元素被鼠标停留。从docs

When a specified event is dispatched on a selected node, the specified listener will be evaluated for each selected element, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element. Listeners always see the latest datum for their element, but the index is a property of the selection and is fixed when the listener is assigned; to update the index, re-assign the listener. To access the current event within a listener, use d3.event.

所以,只是做:

.on("mouseover",function(d,i){ 
    d3.select("body") 
     .append("text") 
     .html("</br>"+d.properties.NAME); 
    d3.select(this) 
     .style("fill", someAwesomeColor); 
}); 

要想从您将鼠标放置在一个 “下一个” 元素做:

.on("mouseover",function(d,i){ 
    d3.select(originalSelection.nodes()[i + 1]) 
     .style("fill", someAwesomeColor); 
}); 

哪里originalSelection是初始选择您打电话.data注意.nodes只适用于d3版本4

+0

真棒,我实际上已经尝试类似 this.attr(东西) 但我想我需要它的d3.select。它像一个魅力。 – zachvac

+0

我想知道我什么时候能达到我们的水平 –

+0

虽然其实我有一个后续问题。是否有可能从数据中获取元素?例如,说每个州都有一个索引,当它被掩盖时,我想改变索引为+1的州的颜色(无论出于何种原因),我该怎么做?在d3中从元素到数据看起来很容易,但相反看起来很具挑战性。 – zachvac