javascript - 在D3中如何为当前特定路径启用鼠标悬停事件?

标签 javascript d3.js

我正在使用d3.js创建世界地图。在该 map 中,我需要为每个国家绑定(bind)mouseover事件。

例如:如果我鼠标悬停印度,我需要仅更改印度的填充(背景)颜色。

我实现了mouseover事件。但我的问题是每当我mouseover在国家(印度)上时,该功能会影响所有国家。我的意思是填充颜色会影响所有国家国家。但它只需要影响当前国家。

我也尝试过使用this,但没有运气。

.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})

请帮助任何人解决我的问题。

我的完整代码

     var width = 1000,
        height = 500;

    var projection = d3.geo.robinson()
        .scale(150)
    //.translate(100,100)
    .precision(.5);

    var path = d3.geo.path()
    //  .attr("class","path")
        .projection(projection);

    var svg = d3.select('#'+id)
        .append('svg')
        .attr("width", width)
        .attr("height", height)
        .attr("style", "background:" + json.bc);


    //shape
    d3.json("world.json", function(error, world) {

         svg                            
            .datum(topojson.feature(world, world.objects.countries))
            .append("path")             
            .on("mouseover", function(){d3.select(this).style("fill", "red");})
            .on("mouseout", function(){d3.select(this).style("fill", "white");})
            .attr("style", "fill:" + json.cbc)          
            .attr("class", "country")
            .attr("d", path)

            ;
    });

鼠标悬停之前

Before MouseOver

鼠标悬停后

After mouseOver

最佳答案

这段代码:

 svg                            
  .datum(topojson.feature(world, world.objects.countries))
  .append("path")
...

说 --> 我有一份数据,请从中画一条路径。

将其更改为:

svg.selectAll(".countries")
  .data(topojson.feature(world, world.objects.countries).features)
  .enter()
  .append("path")
  ...

其中表示 --> 我有多个数据(功能),将数据绑定(bind)到我的选择 (selectAll) 并为每个组件绘制一条路径。

示例 here .

关于javascript - 在D3中如何为当前特定路径启用鼠标悬停事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28199330/

相关文章:

json - 使用d3.json导入本地json文件不起作用

javascript - AngularJS,无法添加模块

d3.js - 字体大小在我的 d3.js 代码中不起作用

php - php javascript 的警报框为空

javascript - 调用 id() 时出现意外标记)

javascript - D3 y轴百分比显示

javascript - D3 条形图(按日期和上下文刷)

javascript - 使用 angular.js 提交表单后添加数据

Javascript 如果 url 然后图像

JavaScript 程序利用其他语言的程序