在 Leaflet 的事件回调中设置图层类名

Set layer className within event callback in Leaflet

我希望通过设置其 className 来设置 geojson 功能的样式。如果像这样直接放置在功能上,这将非常有效:

L.geoJson(geojson, {
    onEachFeature: function (feature, layer) {
        layer.setStyle({className: 'grid-cell'});
    }
}).addTo(map);

使用 .css 文件中定义的样式

path.grid-cell{
  stroke-opacity: 1;
  stroke: #444;
  fill: #aaa;
}

但是,如果添加到功能的事件回调中,它不会工作:

L.geoJson(geojson, {
    onEachFeature: function (feature, layer) {
        layer.on('click', function(e){
          this.setStyle({className: 'grid-cell'});
          this.bringToFront();
        });
    }
}).addTo(map);

令人惊讶的是 setStyle({<style_options>}); 在任何一种情况下都适用于所有其他 L.path 选项 除了 className,例如colorfillOpacityweight

例如

L.geoJson(geojson, {
    onEachFeature: function (feature, layer) {
        // this works
        layer.setStyle({color: '#faa', fillOpacity: 0.4, weight: 1});

        // this works too
        layer.setStyle({className: 'grid-cell'});

        layer.on('click', function(e){
          // and this works
          layer.setStyle({color: '#afa', fillOpacity: 0.4, weight: 2});

          // BUT THIS DOES NOT WORK
          this.setStyle({className: 'grid-cell'});
          this.bringToFront();
        });
    }
}).addTo(map);

知道这里有什么吗? Here's a plunker 说明问题。

有关此问题的讨论,请查看此处:https://github.com/Leaflet/Leaflet/issues/2662。评论之一:

I don't think setStyle should actually change the className. The class is not really a style property, and the logic necessary to handle leaflet- classes seems like a hack. I think a setClassName() or add/removeClass API would be more appropriate.