我按照让我们制作 map tutorial 制作了一张 D3 map M. Bostock 着。
它旨在创建 .subunit.id
类并使用像 .subunit.23 这样的 CSS 为其着色 { fill: #f44242; }
。但是虽然 .subunit
的地址很好,但我无法通过指定其 id
来访问每个单元。有任何想法吗?
TopoJSON 文件可在此处获得
https://gist.github.com/Avtan/649bbf5a28fd1f76278c752aca703d18
<!DOCTYPE html>
<meta charset="utf-8">
<html lang="en">
<style>
.subunit {
fill: #4286f4;
stroke: #efbfe9;}
.subunit.23 { fill: #f44242; }
</style>
<head>
<title>D3 Uzbekisztan map</title>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script> -->
</head>
<body>
<script>
var width = 960,
height = 1160;
var projection = d3.geo.albers()
.center([-10, 40])
.rotate([-75, 0])
.parallels([38, 44])
.scale(4000)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
d3.json("uzb_topo.json", function (error, uzb) {
if (error) return console.error(error);
console.log(uzb);
svg.selectAll(".subunit")
.data(topojson.feature(uzb, uzb.objects.uzb).features)
.enter().append("path")
.attr("class", function(d) { return "subunit " + d.id; })
.attr("d", path);
});
</script>
</body>
</html>
最佳答案
ID 不能以数字开头。现在,您正在设置两个不同的类,最后一个以数字开头。
一个简单的解决方案是删除类名中的空格。所以,这:
.attr("class", function(d) { return "subunit " + d.id; })
应该是这样的:
.attr("class", function(d) { return "subunit" + d.id; })//no space
并相应地设置您的 CSS。
另一种解决方案是在数字前添加一个字母,如下所示:
.attr("class", function(d) { return "subunit " + "a" + d.id; })
因此,您将拥有类“a01”、“a02”、“a03”等...
关于javascript - 无法在 D3 中为 svg 元素着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633883/