我显示了许多可点击的层,点击时会显示这些层,但我想通过在点击该元素时添加类active
,以及在点击其他元素时删除该类,来在视觉上区分开打开的层。
我的密码是
mapboxgl.accessToken = '<my access token>';
var map = new mapboxgl.Map({
container: 'map',
style: '< my style>', // replace this with your style URL
center: [174.7645, -36.8509],
zoom: 10,
pitch: 0,
bearing: 0,
antialias: true
});
map.on('style.load', () => {
map.setFog({});
});
map.on('load', function() {
map.addSource('data', {
type: 'geojson',
data: 'sa2fixedmap.json'
})
// Add a few layers
map.addLayer({
'id': 'KULI',
'type': 'fill',
'source': 'data',
'layout': {
'visibility': 'none'
},
'paint': {
'fill-color': {
property: 'kuli_geomAgg',
stops: [
[0, '#1588ff'],
[.2, '#69ccfa'],
[.5, '#ffffb9'],
[.9, '#ff5959'],
[1, '#ff0101']
]
}
}
}, firstSymbolId);
map.addLayer({
'id': 'Train Station',
'type': 'fill',
'source': 'data',
'layout': {
'visibility': 'none'
},
'paint': {
'fill-color': {
property: 'station1',
stops: [
[0, '#ffffff'],
[4, '#ffacac'],
[6, '#ff2b2b'],
[8, '#ea0000'],
[10, '#7f0000']
]
}
}
}, firstSymbolId);
var alllayersdict = {
'KULI':'KULI',
'Train Station':'transport'
};
// create a dictionary to store the links for each category
var menuLinks = {};
// create a link for each layer and group them by category
for (var key in alllayersdict) {
var theme = alllayersdict[key];
var link = document.createElement('a');
link.href = '#';
link.id = theme;
link.textContent = String(key);
link.onclick = function(e) {
var clickedLayer = this.textContent;
e.preventDefault();
e.stopPropagation();
for (var key2 in alllayersdict) {
if (clickedLayer === key2) {
//class 'active' should be added to the clicked "a" element
map.setLayoutProperty(key2, 'visibility', 'visible');
} else {
//class 'active' should be removed from the "a" element
map.setLayoutProperty(key2, 'visibility', 'none');
}
}
};
var layers = document.getElementById('menu');
layers.appendChild(link);
// create a new HTML menu element for each category
if (!menuLinks.hasOwnProperty(theme)) {
var menu = document.createElement('div');
menu.className = 'menu-category';
var title = document.createElement('h3');
title.textContent = theme;
menu.appendChild(title);
var layers = document.createElement('div');
layers.className = 'menu-layers';
menu.appendChild(layers);
menuLinks[theme] = layers;
document.getElementById('menu').appendChild(menu);
}
// add the link to the corresponding HTML menu element
menuLinks[theme].appendChild(link);
}
我怎样才能做到这一点?
2条答案
按热度按时间ny6fqffe1#
根据代码的设置方式,您可以在
querySelector
方法中使用以下选择器字符串访问link.onclick
事件处理程序的for
循环中的锚<a>
元素:这允许在
if else
代码块中添加或删除.active
类:上面三行代码被添加到
for
循环中,如下所示:1l5u6lss2#
使用“element.classList.add”和“element.classList.remove”