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

查看:28
本文介绍了传单路径:如何设置 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-classname?稍后在我的代码中,我想按特定的类名选择路径.

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 年后,我再次偶然发现了这个问题.我花了2个小时才解开这个谜.下面接受的答案确实有效,但有一个问题.仅当您在图层上调用 addTo(map) 设置 cssClass before 时它才有效.最终在源代码中挖掘它之后,很明显leaflet只在每个路径初始化时设置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.

推荐答案

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

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天全站免登陆