javascript - svg hover 突出显示一个大陆的所有国家
问题描述
我有这张世界地图。当我将鼠标悬停在某个国家/地区上时,我知道如何使每个国家/地区突出显示,但我希望当我将鼠标悬停在该大陆的任何国家/地区时,我希望该大陆的所有国家/地区都突出显示。
解决方案
那张世界地图的组织方式我可以说的不多。有作为类添加的二合字母国家代码(PE:秘鲁)。你必须浏览所有有向图的一些资源,或者看看你是否找到了已经按大陆索引它们的东西。这是创建映射所必需的,这样您就可以知道哪些类对应于哪些大陆。
然后,您可以设置规则,如果某个国家/地区被突出显示,那么您就知道其他国家/地区在同一大陆的组成部分,并且可以突出显示这些国家/地区。
const countryToContinent = {
'CA': 'North America',
'US': 'North America',
// ...
};
const continentToCountries = {
'North America': ['US', 'CA', 'MX', // ...],
// ...
};
const landElements = document.getElementsByClassName('land');
landElements.forEach(land => {
land.addEventListener('hover', event => {
let continent;
land.classList.forEach(className => {
if(className !== 'land'){
if(countryToContinent.hasOwnProperty(className)){
continent = countryToContinent[]
}
}
});
// this is just to be careful, there are a lot of svgs in there
if(continent){
// remove previously highlighted countries/continents
const alreadyHighlightedCountries = document.getElementsByClassName('highlight-block');
alreadyHighlightedCountries.forEach(highlightedCountry => {
highlightedCountry.remove('highlight-block');
});
const countriesToHighlight = continentToCountries[continent];
countriesToHighlight.forEach(country => {
const countrySvg = document.getElementsByClassName(country);
if(!countrySvg.classList.has('highlight-block')){
countrySvg.add('highlight-block');
}
});
}
});
});
分别在你的 CSS 中有这个
.highlight-block {
fill: red !important;
}
推荐阅读
- python - 将列表中的字典附加到熊猫数据框
- javascript - 使用多个条件过滤嵌套数组
- system-verilog - 序列和序列项目有什么区别?
- python - 有没有办法强制 SimpleImputer 返回熊猫数据框?
- yii2 - 如何在 Yii2 模块中包含图像
- java - GrizzlyTestContainer 的 ServletContext
- java - 带有 Cosmos DB 的 Spring Boot 应用程序 SocketException
- tarantool - 在 Tarantool 中处理日期的正确方法是什么?
- php - 通过 PHP 添加 HTML attr
- java - 通过 Selenium 启动外部 VPN 软件