你的bug很微妙。你从一个开始Array
of String
s:
var nationList = ["usa", "france", "italy"];
然后你打电话String.prototype.includes
, 通过path.className
作为一个论点。
if (foundNations.includes(path.className)) { path.classList.add('fadeIn')
在那里,你隐隐约约地assuming that path.className
is a String
。但是,令人惊讶的是,这不是一个String
, 它是SVGAnimatedString https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString!
console.log(path.className)
> [object SVGAnimatedString] {
animVal: "germany",
baseVal: "germany"
}
是的,在某些边缘情况下,SVG 元素的类名称可以在动画过程中修改。
您可能想要做的是使用baseVal的财产SVGAnimatedStrings https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString/baseVal:
console.log(typeof path.className.baseVal)
> "string"
现在一切都应该更接近您期望的方式:
if (foundNations.includes(path.className.baseVal)) {
path.classList.add('fadeIn')
}
console.log(path.className.baseVal);
> "spain fadeIn"
由于另一个假设,您遇到了第二个问题。你是assuming that path.className
仅包含one类名,但是根据文档 https://developer.mozilla.org/en-US/docs/Web/API/Element/className,强调我的:
cName
是代表类的字符串变量或空格分隔的类当前元素的。
事实上,如果您使用浏览器中可用的开发人员工具来检查 SVG 元素,您会看到类似的内容......
<path class="Italy leaflet-interactive" stroke="#ffffff" ....></path>
所以在这种情况下,您假设className.baseVal
将是字符串"Italy"
,但实际上,它需要的值"Italy leaflet-interactive"
.
这里的方法是使用Element.classList https://developer.mozilla.org/en-US/docs/Web/API/Element/classList迭代类名s看看是否any其中匹配给定的
团体。
此外,我认为这是一个例子XY问题 https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem。我想你不想问
如何检查 SVG 路径是否具有匹配的类foo
?
反而
当要素匹配时如何在Leaflet中符号化SVG多边形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);
Leaflet 提供了方便的功能,例如L.Path.setStyle https://leafletjs.com/reference-1.3.0.html#path-setstyle只要您保留对实例的引用,就隐藏了直接处理选择器和 SVG 类的复杂性L.Polygon
周围(在这种情况下,您可以在onEachFeature
打回来)。