【问题标题】:Cannot get D3 .on('mouseover', ...) to work无法让 D3 .on('mouseover', ...) 工作
【发布时间】:2021-04-22 07:09:48
【问题描述】:

我正在学习 D3,我试图通过将鼠标悬停在 SVG 圆圈上来在散点图上显示数据信息。我从 csv 文件中获取数据(数据在太阳系上,包括行星名称、质量和半径)并且所有圆圈都正确显示,但是当我尝试在鼠标悬停时 console.log 数据信息(例如质量)它不记录任何东西。鼠标悬停动作运行正常,但控制台告诉我请求的值是“未定义”。 我哪里搞砸了?这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>

    <style type="text/css">
    body{
        background-color: black;
    }
    #chart{
        background-color: black;
        width: 800px;
        height: 500px;
        border: solid 1px white;
    }
    svg{
        background-color: white;
    }
    .dot{
        stroke: red;
        stroke-width: 1px;
    }
    </style>
    
    <script type="text/javascript" src="https://d3js.org/d3.v6.min.js"></script>
</head>

<body>

    <div id="chart"></div>

    <script type="text/javascript">
        var width = 800;
        var height = 500;
        var circles;
        var svg = d3.select('#chart')
                .append('svg')
                .attr('width', width + 'px')
                .attr('height', height + 'px');

        d3.csv('astro.csv').then(function(data){

            xScale = d3.scaleLinear()
                .domain([0,500])
                .range([0, 800]);

            circles = svg.selectAll('.dot')
                .data(data)
                .enter()   
                .append('circle')
                .attr('class', '.dot')
                .attr('cx', function(d){
                    return xScale(d.mass);
                })
                .attr('cy', 100)
                .attr('r', 20)
                .on('mouseover', function(d){
                    console.log(d.mass);
                })                
        });
    </script>
</body>
</html>

【问题讨论】:

    标签: d3.js onmouseover


    【解决方案1】:

    自 D3 V6 起,所有鼠标事件处理程序都有一个事件作为第一个参数传递,数据作为第二个参数传递。在 V5 或更早版本中,您的代码将可以工作。

    V6 或更高版本:

    .on('mouseover', (event, d) => console.log(d.mass));
    

    V5 或更早版本:

    .on('mouseover', d => console.log(d.mass));
    

    【讨论】:

      猜你喜欢
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2011-11-14
      相关资源
      最近更新 更多