【问题标题】:How do I permanently select a line with the click event in d3?如何在 d3 中永久选择带有点击事件的行?
【发布时间】:2023-01-23 08:27:21
【问题描述】:

我有多线图,我想在其中单击一条线并永久突出显示它。我在单击事件中使用了以下代码,但是在我单击并移动鼠标后,该行返回。

希望有人能帮助我!

编辑:我还有一个包含在代码 sn-p 中的 mouseover 和 mouseout 事件。

diagam.on('click', countryClick)
      .on('mouseover, countryOver)
      .on('mouseout, countryOut);

  //Mouse event functions
        function countryOver(event, d) {
            d3.select(this)
                .style('stroke', 'black')
                .style('stroke-width', 5)
                .attr('id', 'countryOver')
            .selectAll('g')
                .append('text')
                .attr('class', 'tile-text')
                .attr('x', x(dataByCountry.year) / 2)
                .attr('y', y(dataByCountry) / 2)
                .attr('text-anchor', 'middle')
                .attr('font-size', '50')
                .attr('fill', 'black')
                .text(dataByCountry.name);

        }

        function countryOut(event, ) { 
            d3.select(this)
                .style('stroke', 'green')
                .style('stroke-width', 1.5)
            .selectAll('g')
                .append('text')
                .attr('class', 'tile-text')
                .attr('x', x(dataByCountry.year) / 2)
                .attr('y', y(dataByCountry) / 2)
                .attr('text-anchor', 'middle')
                .attr('font-size', '50')
                .attr('fill', 'black')
                .text(dataByCountry.name)
        }

        function countryClick(event, d){
            d3.select(this)
            .style('stroke', 'red')
            .style('stroke-width', 7)
        .selectAll('g')
            .append('text')
            .attr('class', 'tile-text')
            .attr('x', x(dataByCountry.year) / 2)
            .attr('y', y(dataByCountry) / 2)
            .attr('text-anchor', 'middle')
            .attr('font-size', '50')
            .attr('fill', 'black')
            .text(dataByCountry.name)
        }

【问题讨论】:

  • 你也有一个在 mouseOut 上调用的函数吗?
  • 是的,我愿意。这就是点击不是永久性的原因吗?
  • 这取决于您在此功能中执行的操作。你能分享一下吗?检查您是否没有更改代码中其他地方的线条颜色。
  • 我确实更改了上面的代码 sn-p。我确实有一个 mouseout 和 mouseover 事件,它们突出显示了一行。

标签: javascript d3.js mouseevent mouseclick-event


【解决方案1】:

如果您想在鼠标悬停在该行上时突出显示该行并在单击它时更改其颜色,您可以使用 CSS 根据其状态设置路径样式。

看看这个例子:https://codepen.io/ccasenove/pen/zYaoGpN

最初路径只有 line 类,所以我们可以使用 d3 选择它们,颜色在 CSS 中设置为黑色。在鼠标悬停时,类 over 被设置在元素上,由于 CSS 规则它变成绿色。在 mouseout 上,类 over 被删除。当点击路径时,selected 类被设置为将颜色更改为红色。

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2013-01-07
    相关资源
    最近更新 更多