我有一个数组和一些 svg path
元素(我正在使用 leaflet map )。我需要检查路径的类是否与数组中的某个值匹配,如果是,则向其添加一个类 fadeIn
。
var foundNations = ["usa", "France", "Italy"];
document.querySelectorAll('path').forEach(path => {
if (foundNations.includes(path.className)) {
path.className.add('fadeIn');
console.log(path.className);
}
});
(function($) {
var map = L.map('map').setView([45.4655171, 12.7700794], 2);
map.fitWorld().zoomIn();
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.light'
}).addTo(map);
var mapHalfHeight = map.getSize().y / 2,
container = map.zoomControl.getContainer(),
containerHalfHeight = parseInt(container.offsetHeight / 2),
containerTop = mapHalfHeight - containerHalfHeight + 'px';
container.style.position = 'absolute';
container.style.top = containerTop;
map.scrollWheelZoom.disable();
var southWest = L.latLng(-89.98155760646617, -180),
northEast = L.latLng(89.99346179538875, 180);
var bounds = L.latLngBounds(southWest, northEast);
map.setMaxBounds(bounds);
map.on('drag', function() {
map.panInsideBounds(bounds, { animate: false });
});
// get color depending on population density value
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
function style(feature) {
return {
weight: 1,
opacity: 1,
color: '#ffffff',
dashArray: '',
fillOpacity: 0,
fillColor : '#FF0080',
className: feature.properties.name
};
}
var geojson;
function selectNation(e) {
}
function onEachFeature(feature, layer) {
layer.on({
click: selectNation
});
}
geojson = L.geoJson(statesData, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
})( jQuery );
#map {
width: 100vw;
height: 100vh;
}
.fadeIn {
fill: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" rel="stylesheet"/>
<script src="https://www.jikupin.com/world.json"></script>
<div id='map'></div>
最佳答案
你的错误很微妙。您从 Array
开始的String
s:
var nationList = ["usa", "france", "italy"];
那么您调用String.prototype.includes
,路过path.className
作为一个论点。
if (foundNations.includes(path.className)) { path.classList.add('fadeIn')
在那里,您隐含地假设 path.className
是 String
。但是,令人惊讶的是,这不是 String
,这是一个 SVGAnimatedString
!
console.log(path.className)
> [object SVGAnimatedString] {
animVal: "germany",
baseVal: "germany"
}
是的,在某些边缘情况下,可以在动画期间修改 SVG 元素的类名称。
您可能想要做的是使用 baseVal
property of the SVGAnimatedString
s :
console.log(typeof path.className.baseVal)
> "string"
现在一切都应该更接近您期望的方式:
if (foundNations.includes(path.className.baseVal)) {
path.classList.add('fadeIn')
}
console.log(path.className.baseVal);
> "spain fadeIn"
<小时/>
<小时/>
由于另一个假设,您遇到了第二个问题。您假设path.className
仅包含一个类名,但是 according to the documentation ,强调我的:
cName
is a string variable representing the class or space-separated classes of the current element.
事实上,如果您使用浏览器中提供的开发人员工具来检查 SVG 元素,您会看到类似的内容...
<path class="Italy leaflet-interactive" stroke="#ffffff" ....></path>
因此,在本例中,您假设 className.baseVal
将是字符串 "Italy"
,但实际上,它的值为 "Italy leaflet-interactive"
.
这里的方法是使用 Element.classList
迭代类名s以查看其中是否有任何与给定的匹配
组。
此外,我认为这是 XY problem 的一个实例。我认为你不想问
How to check if a SVG path has a class that maches
foo
?
而是
How to symbolize a SVG polygon in Leaflet when the feature matches
foo
?
因为我认为将支票移至 style
更为优雅。回调函数,如:
geojson = L.geoJson(statesData, {
style: function(feature){
var polygonClassName = feature.properties.name;
if (nationList.contains(feature.properties.name)) {
polygonClassName += ' fadeIn';
}
return {
weight: 1,
opacity: 1,
color: '#ffffff',
dashArray: '',
fillOpacity: 0,
fillColor : '#FF0080',
className: polygonClassName
};
},
onEachFeature: onEachFeature
}).addTo(map);
传单提供了便捷的功能,例如 L.Path.setStyle
只要您保留对 L.Polygon
实例的引用,就隐藏了直接处理选择器和 SVG 类的复杂性。周围(在这种情况下,您可以在 onEachFeature
回调中执行此操作)。
关于javascript - 如何检查 svg 路径是否具有与数组中的值匹配的类,如果是,则添加一个新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50718464/