简体   繁体   English

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

[英]Set layer className within event callback in Leaflet

I'm looking to set a geojson feature's style via setting its className . 我想通过设置className设置geojson功能的样式。 This works perfectly fine if placed directly on the feature like so: 如果直接放在这样的功能上,这种方法非常好:

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

with the style defined in a .css file 使用.css文件中定义的样式

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

However, it does not work if added within a feature's event callback: 但是,如果一个功能的事件回调中添加它工作:

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

What's surprising is that setStyle({<style_options>}); 令人惊讶的是setStyle({<style_options>}); work in either case for every other L.path option besides className , eg color , fillOpacity , weight , etc. 除了 className 之外 ,在任何一种情况下都可以使用其他每个L.path选项,例如colorfillOpacityweight等。

Eg 例如

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);

Any idea what's up here? 知道这里有什么? Here's a plunker illustrating the issue. 这是一个说明问题的傻瓜

For a discussion of this issue, look here: https://github.com/Leaflet/Leaflet/issues/2662 . 有关此问题的讨论,请访问: https//github.com/Leaflet/Leaflet/issues/2662 One of the comments: 其中一条评论:

I don't think setStyle should actually change the className. 我认为setStyle实际上不应该改变className。 The class is not really a style property, and the logic necessary to handle leaflet- classes seems like a hack. 这个类实际上不是一个样式属性,处理leaflet-类所需的逻辑看起来像是一个黑客。 I think a setClassName() or add / removeClass API would be more appropriate. 我认为setClassName()add / removeClass API更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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