宣传单张路径:如何设置CSS类? [英] Leaflet path: how can I set a css class?

查看:63
本文介绍了宣传单张路径:如何设置CSS类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切,但这是一些代码,所以您明白我的意思了.

Well the title says it all but here is some code so you see what i mean.

function eachFeature(feature, layer) {
     layer.on({
         mouseover: highlightFeature,
         mouseout: resetHighlight,
     });
}
geojson = L.geoJson(geojson_raw, { style: style, onEachFeature: eachFeature });
geojson.addTo(map);

geojson_raw是保存在javascript变量中的geojson对象. style只是返回具有某些样式属性的对象的函数. highlightFeature/resetHighlight是用于根据mousein/out事件更改这些样式的功能.

geojson_raw is the geojson object which is held in a javascript variable. style is just the function that returns an object with some style attributes. highlightFeature / resetHighlight are functions to change these styles according to mousein/out events.

因此此代码有效,我已经知道如何通过对用户事件做出反应来更改样式. 但是,如何在根据我的geojson数据创建的路径上设置实际的CSS类名称?稍后在我的代码中,我想通过特定的类名选择路径.

So this code works and I already know how to change styles by reacting on user events. But how can I set an actual css-classname on the paths that are created from my geojson data? Later in my code I would like to select paths by a specific classname.

更新

2年后,我再次迷失了这个问题.我花了两个小时解决了这个谜.下面接受的答案确实有用,但是有一个陷阱.仅当您在图层上调用addTo(map)之前,在之前设置了cssClass时,此方法才有效.最终在源代码中对其进行了挖掘之后,可以清楚地看到,只有在初始化每个路径时,传单才会设置cssClass.

2 years later I stumbled over this issue once again. And it took me 2 hours to solve the mystery. The accepted answer below does work, BUT there is a catch. It only works if you set the cssClass before you call addTo(map) on the layer. After finally digging it up in the source code it became clear that leaflet only sets the cssClass when each path gets initialised.

推荐答案

下面的代码将允许您在geoJosn方法使用D3创建路径之后添加类.

The code below will allow you to add a class after the paths are created by the geoJosn method with D3.

var svg = d3.select(map.getPanes().overlayPane).append("svg"),
g = svg.append("g").attr("class", "your_class");

但是,如果要在创建时仅使用传单添加它们,请尝试以如下所示的style(feature)方法返回它们:

However, if you want to add them on creation using only leaflet, try returning them in the style(feature) method like this:

function style(feature) {
        return {
          weight: 1,
          opacity: .5,
          fillOpacity: 0.7,
          className: feature.properties.name_of_node
        };
}

那对我来说真的很好.

这篇关于宣传单张路径:如何设置CSS类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆