[英]Cannot color svg elements in D3
我按照Bostock的地圖教程制作了D3地圖。
它旨在創建.subunit.id
類,並使用CSS如.subunit.23 { fill: #f44242; }
.subunit.23 { fill: #f44242; }
。 但是,盡管.subunit
很.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”等類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.