How do you add a class to a Leaflet marker?

2020-03-09 07:10发布

I'm using custom divIcons for my Leaflet markers. I want to add a border to whatever marker I click on, with some simple CSS:

.selectedMarker {
border: 10px solid gold;
}

However, the following with jQuery doesn't work:

$(marker).addClass('selectedMarker');

Then I tried to use Leaflet's own addClass() method. I tried to call use it in the following ways:

marker.addClass('selectedMarker');
L.addClass(marker, 'selectedMarker');
addClass(marker, 'selectedMarker');
DomUtil.addClass(marker, 'selectedMarker');

None of these work. How do I add the selectedMarker class to my marker?

3条回答
我想做一个坏孩纸
2楼-- · 2020-03-09 07:46

I have done it by adding a class to the marker with

var marker = L.marker(loc);
marker.on('click', function() {
    $(marker._icon).addClass('selectedMarker');
}

and then use the css

.leaflet-marker-icon.selectedMarker{
  //your css
}
查看更多
啃猪蹄的小仙女
3楼-- · 2020-03-09 07:55

without using jQuery,

marker._icon.classList.add("className");
查看更多
家丑人穷心不美
4楼-- · 2020-03-09 08:02

In 1.0 and 0.7 you can use L.DomUtil to add remove classes from a DOM element:

L.DomUtil.addClass(marker._icon, 'className');
L.DomUtil.removeClass(marker._icon, 'className');
查看更多
登录 后发表回答