简体   繁体   中英

Changing legend background color with css/javascript

I am new to css/javascript! I apologize if this is a simple question. I am trying to add a legend to a map but I can't figure out how to make the legend background white. Right now, the legend is transparent.

Here is what I have in css

#legend {font-family: Arial, sans-serif;
   background: #fff;
    padding: 10px;
    margin: 10px;
    border: 3px solid #000;

Then for js

var legend = L.control({position: 'topright'});

    legend.onAdd = function (mymap) {

        var div = L.DomUtil.create('div', 'legend'),
        grades = ["Library", "Parking Lot"],
        labels = ["http://maps.google.com/mapfiles/ms/micons/rangerstation.png", "http://maps.google.com/mapfiles/ms/micons/parkinglot.png"];

// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
        div.innerHTML +=
    (" <img src="+ labels[i] +" height='50' width='50'>") + grades[i] + '<br>';
}
return div; } legend.addTo(mymap);

Edit: This is what the map looks like right now with the legend

I'm not entirely sure if I understood your posted code, but, you create a new element with var div = L.DomUtil.create('div', 'legend') , named div , right and you'd like to add background to it ? If so, try doing something like:

var legend = L.control({position: 'topright'});

    legend.onAdd = function (mymap) {

        var div = L.DomUtil.create('div', 'legend'),
        grades = ["Library", "Parking Lot"],
        labels = ["http://maps.google.com/mapfiles/ms/micons/rangerstation.png", "http://maps.google.com/mapfiles/ms/micons/parkinglot.png"];

        // Add the ID to the div element that will match #legend
        div.id = "legend";

// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
        div.innerHTML +=
    (" <img src="+ labels[i] +" height='50' width='50'>") + grades[i] + '<br>';
}
return div; } legend.addTo(mymap);

So, try adding the legend id to the div element inside the function you have. If I misunderstood your question and this does not work, hit me up to change my answer.

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