简体   繁体   中英

Cannot color svg elements in D3

I made a D3 map following Let's make a map tutorial by M. Bostock.

It is intended to create .subunit.id class and color it using CSS like .subunit.23 { fill: #f44242; } .subunit.23 { fill: #f44242; } . But while .subunit is adressed well I can not reach each unit by specifying its id . Any ideas?

TopoJSON file is available here
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>

IDs cannot start by a number. Right now, you're setting two different classes, and the last one start with a number.

A simple solution is removing the space in your class name. So, this:

.attr("class", function(d) { return "subunit " + d.id; })

Should be this:

.attr("class", function(d) { return "subunit" + d.id; })//no space

And set your CSS accordingly.

Another solution is adding a letter before the number, like this:

.attr("class", function(d) { return "subunit " + "a" + d.id; })

So, you'll have the classes "a01", "a02", "a03" etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM