首页 > 解决方案 > 在 Choropleth 中突出显示状态

问题描述

我正在关注这个例子: http ://bl.ocks.org/ElefHead/ebff082d41ef8b9658059c408096f782

但是,我不明白为什么当我只画三件事(县、州、州边界)时。当一个状态悬停时,我只想改变填充颜色并获得流畅的体验。

jsfiddle在这里: https ://jsfiddle.net/kick_out/jq3w6xft/10/

当前代码具有与 bl.ocks 示例类似的 css 样式:当我删除县部分时,我没有突出显示。

.county-boundary:hover, .state:hover {
  fill: orange
}

标签: javascriptd3.jssvg

解决方案


首先,州级是state,不是states。但是这个问题不仅仅是一个错字问题,这里还有一个更大的问题:

您将状态的填充设置为none(使用它们的父组 CSS)。这就是为什么你悬停没有效果。在 SVG 中,默认pointer-events值为visiblePainted其中

只有当可见性属性设置为可见时,该元素才能成为指针事件的目标,例如,当鼠标光标位于元素的内部(即“填充”)并且填充属性设置为除没有。(强调我的)

因此,您应该将它们设置pointer-eventsall.

此外,如果要显示县,请更改附加顺序。

这是您进行这些更改的代码:

async function drawMap() {
  var svg = d3.select("body").append('svg')
    .attr("height", 600)
    .attr("width", 1000)

  var map = await d3.json('https://d3js.org/us-10m.v1.json')
  var path = d3.geoPath()
  var mouseOver = function(d) {
    d3.select(this)
  }
  var mouseOut = function(d) {}
  svg.append("g")
    .attr('id', 'counties')
    .selectAll("path")
    .data(topojson.feature(map, map.objects.counties).features)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "county-border")
  svg.append("g")
    .attr("id", "states")
    .selectAll("path")
    .data(topojson.feature(map, map.objects.states).features)
    .enter().append("path")
    .attr("d", path)
    .attr('class', 'states')

  svg.append("g")
    .attr("id", "states")
    .selectAll("path")
    .data(topojson.feature(map, map.objects.states).features)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "state")
    .attr("pointer-events", "all");

  svg.append("g")
    .attr("id", "counties")
    .selectAll("path")
    .data(topojson.feature(map, map.objects.counties).features)
    .enter().append("path")
    .attr("d", path)
    .attr("class", "county-boundary")
    .attr("pointer-events", "none")
}
drawMap()
#states {
  fill: none;
  stroke: green;
  stroke-width: 1.9px;
}

#states .active {
  display: none;
}

#state-borders {
  fill: none;
}

#counties {
  fill: none;
}

.county-boundary {
  fill: none;
  stroke: lightgrey;
  stroke-width: 0.7px;
}

.state:hover {
  fill: orange;
}

#sliderContainer {
  text-align: center;
  position: relative;
  left: 10px;
}
<!DOCTYPE html>
<html lang="en">
  <title>County Map</title>

  <body>
    <div id="wrap"></div>
    <script src="https://d3js.org/d3.v5.js"></script>
    <script src="https://d3js.org/topojson.v3.min.js"></script>
    <script src="map.js"></script>
  </body>

</html>


推荐阅读