我正在使用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)
;
});
鼠标悬停之前
鼠标悬停后
最佳答案
这段代码:
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/