【问题标题】:Why is the hover state behaviour removed?为什么要删除悬停状态行为?
【发布时间】:2019-09-28 08:42:18
【问题描述】:

我有一个 D3 生成的地图,它需要能够动态更改绘制路径的填充元素。原始路径被生成并分配了一类“边界”。当用户将光标悬停在国家/地区上时,悬停行为设置为将该国家/地区变为黄色。但是,如果我随后动态更改国家/地区的填充颜色,例如使用 d3.selectAll-(我简化了下面的示例,以便通过取消注释最后一部分来模拟此行为),悬停行为将停止工作。类没有改变,那么为什么现在没有发生悬停行为.. 是否有解决方法?

CSS

.countryMap{
 width: 500px;
 height: 500px;
 position: relative;
}

.boundaries{
 fill:green;
}

.boundaries:hover{
 fill:yellow;
}

Javascript

const countryMap = {};
      const FILE = `aus.geojson`; // the file we will use
      var svg = d3
        .select('div.country__map')
        .append('svg')
        .attr('width',200)
        .attr('height',200)
        .attr('preserveAspectRatio', 'xMinYMin meet')
        .attr('viewBox','770 270 200 150')

        d3.json(FILE).then(function (outline) {
        countryMap.features = outline.features;

        // choose a projection
        const projection = d3.geoMercator();
        // create a path generator function initialized with the projection
        const geoPath = d3.geoPath().projection(projection);
        drawOutline();

        function drawOutline() {
          svg
            .selectAll('path.boundaries') // CSS styles defined above
            .data(countryMap.features)
            .enter()
            .append('path')
            .attr('class', 'boundaries')
            .attr('d', geoPath)
            // .style('fill', d => {
            //   return 'green';
            // })
        }
        })

【问题讨论】:

  • SVG 子元素上的悬停状态有很多问题 - 最好使用 JavaScript 手动更改类。

标签: javascript css d3.js svg


【解决方案1】:

正如@Michael 所说,使用 js 手动添加或删除类会更好。

D3 为我们提供了可用于添加和删除类的 mouseover 和 mouseout 事件。

在悬停时,我们在元素上应用“活动”类。

svg
   .selectAll('path.boundaries')
   .data(countryMap.features)
   .enter()
   .append('path')
   .attr('class', 'boundaries')
   .attr('d', geoPath)
   .on('mouseover', function () {
      d3.select(this).classed("active", true)  
   })
   .on('mouseout', function () {
      d3.select(this).classed("active", false)
   })

我们还需要根据这些变化更新 CSS。 您可以将 CSS 更新为:

.boundaries{
 fill:green;
}

.boundaries.active{
 fill:yellow;
}

【讨论】:

    猜你喜欢
    • 2013-07-02
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多