使用 Mapbox GL JS 根据单击的图层设置不同样式的弹出窗口

Style popups differently depending on the clicked layer using Mapbox GL JS

我目前正在尝试根据弹出窗口所在的层为我的弹出窗口提供不同的背景(即我有一个名为 Indigenous Sites 的层,我希望弹出窗口的背景与其他层不同)。

我试过给弹出窗口一个类名,但我不确定如何在 CSS 中正确调用它。

下面是我的 html 文档中的弹出脚本示例(用于 2 个不同层弹出窗口的脚本):

// popup for the Other European Sites layer 
map.on('click', 'Other European Sites', function (e) {
new mapboxgl.Popup()
    .setLngLat(e.lngLat)
    .setHTML('<h2>' + 'European Site' + '</h2>' + 
        '<p>' + e.features[0].properties.placeName + '</p>' + 
        '<h2>' + 'Story' + '</h2>' + 
        '<p>' + e.features[0].properties.Story + '</p>' + 
        '<h2>' + 'Latitude' + '</h2>' + 
        '<p>' + e.features[0].properties.latitude + '</p>'  + 
        '<h2>' + 'Longitude' + '</h2>' + 
        '<p>' + e.features[0].properties.longitude + '</p>')
    .addTo(map);
});

// popup for the Other Indigenous Sites layer
map.on('click', 'Other Indigenous Sites', function (e) {
new mapboxgl.Popup({className: 'popupCustom'})
    .setLngLat(e.lngLat)
    .setHTML('<h2>' + 'Indigenous Site' + '</h2>' + 
        '<p>' + e.features[0].properties.placeName + '</p>' + 
        '<h2>' + 'Story' + '</h2>' + 
        '<p>' + e.features[0].properties.Story + '</p>' + 
        '<h2>' + 'Latitude' + '</h2>' + 
        '<p>' + e.features[0].properties.latitude + '</p>'  + 
        '<h2>' + 'Longitude' + '</h2>' + 
        '<p>' + e.features[0].properties.longitude + '</p>')
    .addTo(map);
});

这是我当前的 CSS,它为我的所有弹出窗口提供了相同的背景:

.mapboxgl-popup-content {
overflow-y: scroll;
background-color: #000000;
}

我该如何为弹出窗口分配不同的类名并在 CSS 中调用它们,以便我可以为每一层设置不同的背景?

非常感谢您的意见!

className 是将应用于弹出容器(包含 "mapboxgl-popup-content" 元素)的 CSS class 名称。因此,如果您希望 "Other Indigenous Sites" 图层具有黄色弹出窗口,您可以这样做:

.mapboxgl-popup-content {
    overflow-y: scroll;
    background-color: #000000;
}

.popupCustom .mapboxgl-popup-content {
    background-color: yellow;
}

但是请注意,此功能非常recently added and I don't think it has been released yet. (It's not in the published docs)。