首页 > 解决方案 > 为什么鼠标悬停事件不适用于 d3.js 投影中的所有状态?

问题描述

我很难理解为什么鼠标悬停事件在我的投影中不一致地发生。我希望突出显示鼠标悬停的状态,该状态在大多数情况下都有效,但对于某些状态,鼠标悬停事件根本不会发生。谁能帮我理解这里的问题是什么?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <script src="https://unpkg.com/topojson-client@3"></script>
</head>
<body>
    <script>
        const width = 1000;
        const height = 600;

        const path = d3.geoPath(null);

        const svg = d3.select("body")
            .append("svg")
            .attr("height", height)
            .attr("width", width)
            .style("display", "block")
            .style("margin", "auto");

        d3.json("https://d3js.org/us-10m.v1.json").then(data => {
            svg.selectAll(".states")
                .data(topojson.feature(data, data.objects.states).features)
                .join("path")
                .attr("d", path)
                .style("fill", "none")
                .attr("class", "states")
                .style("stroke", "black")
                .style("stroke-width", "2px")
                .style("cursor", "pointer")
                .on("mouseover", function(d, i) {
                    d3.select(this)
                        .transition(100)
                        .style("fill", "#6d7899");
                })
                .on("mouseout", function(d, i) {
                    d3.select(this)
                        .transition(100)
                        .style("fill", "none");
                });
        });
    </script>
</body>
</html>

标签: d3.jsmouseover

解决方案


我能够确定问题的根源。您必须将“填充”属性设置为实际值,而不是“无”,鼠标悬停事件才能正确识别投影中的地理边界。


推荐阅读