1

我目前在我的地图中有县突出显示和删除鼠标悬停和鼠标悬停的突出显示。我想为单击事件设置单独的颜色 - 这意味着所选县将保持这种新颜色,直到单击新县,而与任何 mouseover 或 mouseout 事件无关。我目前在单击时更改县的颜色,但仅当鼠标悬停在元素上时。

这是我目前拥有的:

        .call(d3.helper.tooltip()
          .text(function(d){ return 'County: '+ newDict[d.id][0] + '<br />HOPE Dollars: $' +commasFormatter(newDict[d.id][1]); }))
          .on('mouseover', function(d){ d3.select(this).style({fill: '#FAAE0A', stroke: '#F08C00', opacity:'0.5', 'stroke-width':'3px'}); })
          .on('mouseout', function(d){ d3.select(this).style({fill: '', stroke: '', opacity:'1', 'stroke-width':''}); })
        .on("click", function(d) {
        $('#nameCounty').html(''+ newDict[d.id][0] +'')
        d3.select(this).style({fill: '#F08C00', stroke: '', opacity:'1', 'stroke-width':''});
        });
4

1 回答 1

7

如果您想在单击另一个项目时“取消突出显示”一个项目,您需要一种方法来找到先前突出显示的项目并取消其“突出显示”状态。

一种方法是为class突出显示的项目分配一个特定的项目,以便您稍后再次找到它。是否使用它来设置项目的样式并不重要。

例如,在click下面将首先通过搜索具有该类的项来找到先前突出显示的项,从该项.highlighted中删除.highlighted该类,然后将该.highlighted类分配给当前项:

.on("click", function () {
            // Find previously selected, unselect
            d3.select(".selected").classed("selected", false);

            // Select current item
            d3.select(this).classed("selected", true);
        });

你可以在这个 fiddle中尝试一下。

于 2013-08-04T13:50:21.953 回答