javascript - d3.js topojson 县/州 map 上的鼠标移动功能 - 按住单击可选择多个县

标签 javascript d3.js topojson

利用 Mike Bostocks 美国各县区 block :https://bl.ocks.org/mbostock/4122298

目标是创建一个鼠标移动函数,在事件期间鼠标移动将突出显示所有选定的县。当前示例仅突出显示使用 :hover 并且不保留选择。

<!DOCTYPE html>
<style>

.counties :hover {
  fill: red;
}

.county-borders {
  fill: none;
  stroke: #fff;
  stroke-width: 0.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}

</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>

var svg = d3.select("svg");

var path = d3.geoPath();

d3.json("https://d3js.org/us-10m.v1.json", function(error, us) {
  if (error) throw error;

  svg.append("g")
      .attr("class", "counties")
    .selectAll("path")
    .data(topojson.feature(us, us.objects.counties).features)
    .enter().append("path")
      .attr("d", path);

  svg.append("path")
      .attr("class", "county-borders")
      .attr("d", path(topojson.mesh(us, us.objects.counties, function(a, b) { return a !== b; })));
});

</script>

最佳答案

请参阅我的片段 - 这就是我的理解。您需要使用 JavaScript 事件和类,因为 CSS 无法更改状态。

var svg = d3.select("svg");

var path = d3.geoPath();

d3.json("https://d3js.org/us-10m.v1.json", function(error, us) {
  if (error) throw error;

  svg.append("g")
    .attr("class", "counties")
    .selectAll("path")
    .data(topojson.feature(us, us.objects.counties).features)
    .enter()
    .append("path")
    .attr("d", path);

  // the following block is new, adding JS events
  let hoverEnabled = false;
  svg.on('mousedown', x => hoverEnabled = true)
    .on('mouseup', x => hoverEnabled = false)
  svg.selectAll('.counties path').on('mouseover', function() {
    if (hoverEnabled) {
      this.classList.add('hovered');
    }
  });
  
  svg.append("path")
     .attr("class", "county-borders")
    .attr("d", path(topojson.mesh(us, us.objects.counties, function(a, b) { return a !== b; })));
});
/* paths with class "hovered" need to be selected here, too */
.counties .hovered, .counties :hover {
  fill: red;
}

.county-borders {
  fill: none;
  stroke: #fff;
  stroke-width: 0.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}
<!DOCTYPE html>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>

关于javascript - d3.js topojson 县/州 map 上的鼠标移动功能 - 按住单击可选择多个县,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955816/

相关文章:

javascript - 如何克隆和进行多次替换

javascript - 从数组中获取唯一 ID 的总和

javascript - 这个 JSON 文件有什么问题?

javascript - D3 map - 标记缩放

javascript - D3 Topojson 圆,半径以英里为单位

node.js - 无法安装 Topojson

javascript - 如何在 Angular JS 中的动画之后触发 Controller 功能

javascript - 当输入处于事件状态时,如何使用 angularjs 显示帮助消息?

javascript - d3 的面积图不在 jsp 页面上呈现,但在 html 上工作正常

javascript - 使用 d3.js 计算平均 json