是否可以使用onclick隐藏其他路径?

时间:2016-04-28 16:16:12

标签: javascript d3.js

我有一个topojson文件,如下所示(此处只显示一个“节点”):

{  
 "type":"Polygon",
 "properties":{  
 "OBJECTID":156,
 "geoid10_1":360610009001000,
 "ALAND10": 0,
 "AWATER10": 16690,
 "latitude":40.7055747,
 "longitude":-74.010762,
 "cnt_client":5,
 "blocks_lis":"360610050004001|360593025011000|360610065001005",
 "Shape_Leng":0.00507281682202,
 "Shape_Area":0.000001463445362
},
"arcs":[  
[  
  671,
  672,
  673,
  674
 ]
]
}

并在地图上显示曼哈顿块,在cnt_client值之后着色。 当地图加载时,当cnt_client为0时,avery块从白色显示为10时显示为dark_blue。

是否可以使用点击功能: 1)保持单击的块按原样显示 2)同时显示block_lis中的块(每个块都有一个geoid10_1标识符) 3)隐藏所有其他块

enter image description here

pathes
                .data(topojson.feature(geodata,geodata.objects.collection).features)
                .enter()
                .append("path")
                .attr("d",path)
                .style("fill", function(d){ return color(d.properties.cnt_client); })
                .style("stroke",  "white")
                .style("stroke-width", "0.7")
                .on('mouseover', tip.show)
                .on('mouseout', tip.hide)
                .on("click", function(d) {

                    ???

                }

1 个答案:

答案 0 :(得分:1)

首先为每个路径分配其唯一geoid10_1值作为id。然后你可以使用CSS而不是选择器:

.on("click", function(d) {
  // show everyone
  d3.selectAll('path')
    .style('opacity', 1);
  // find the ids of ones to continue to show
  var notIds = [d.geoid10_1].concat(d.blocks_lis.split("|")),
      cssSelector = "path";
  // build a css selector string
  notIds.forEach(function(d1){
    cssSelector += ':not([id="' + d1 + '"])';
  });
  // hide those NOT in our list
  d3.selectAll(cssSelector)
    .style("opacity", 0);      
});

这里有一些代码显示了隐藏被点击的一个和下一个的方法:



<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
    <style>
      path {
        stroke: steelblue;
        stroke-width: 10px;
      }
    </style>
  </head>

  <body>
    <svg width="300" height="300">
      <path id="1" d="M0,0L200,200"></path>
      <path id="2" d="M0,0L150,200"></path>
      <path id="3" d="M0,0L100,200"></path>
      <path id="4" d="M0,0L050,200"></path>
    </svg>
    <script>
      
      d3.selectAll('path')
        .data([{},{},{},{}])
        .on('click', function(d){
        
          console.log(d);
        
          d3.selectAll('path')
            .style('opacity', 1);
        
          if (d.toggle) {
            d.toggle = false;
            return;
          }
        
          var self = d3.select(this),
              id = +self.attr('id'),
              nId = (id < 4) ? id + 1 : 1;
              
          d3.selectAll('path:not([id="' + id + '"]):not([id="' + nId + '"])')
            .style('opacity', 0);
        
          d.toggle = true;
          
        })
      
    </script>
  </body>

</html>
&#13;
&#13;
&#13;