在鼠标悬停一个状态时,使用d3 map更改其他状态的颜色

时间:2014-07-19 06:46:37

标签: javascript d3.js

我认为我的标题总结了我的问题。如果我将鼠标悬停在d3地图中的一个状态上,如何更改预设的其他状态组的颜色?

我可以做点像......

.on("mouseover", function(d,i) {
   if this == (one of the present map selections){
     d3.select({theotherdataname}}.parentNode.appendChild({{theotherdataname??}})).transition().duration(300)
            .style({'stroke-opacity':1,'stroke':'#F00'});
         } 
      }
 });

好的,这是可怕的代码。但我想提供一些东西。

有人可以指出我正确的方向吗?

也许我需要完全更新图表数据?

1 个答案:

答案 0 :(得分:2)

使用D3的filter方法查找所有其他状态,然后应用样式。

http://devdocs.io/d3/selections#filter

DEMO:http://jsbin.com/yejuwa/2/edit

JS:

document.addEventListener('DOMContentLoaded', function(){

  d3.select('#specific').on('mouseover', function(d, i) {

    var currentState = this;
    var thoseStates = d3
      .selectAll('.those')[0]
      .filter(function(state) {
        return state !== currentState;
      });

    d3.selectAll(thoseStates)
      .transition()
      .duration(300)
      .style({
        'stroke-opacity': 1,
        'stroke': '#f00'
      });

  });

});

HTML:

<body>

  <svg width="150" height="150">
    <circle id="specific" class="these" cx="75" cy="75" r="50" fill="yellow" stroke="blue" stroke-width="4" />
  </svg>

  <svg width="150" height="150">
    <rect class="those" width="50" height="50" fill="pink" stroke="green" stroke-width="4" />
  </svg>

</body>