首页 > 解决方案 > svg hover 突出显示一个大陆的所有国家

问题描述

我有这张世界地图。当我将鼠标悬停在某个国家/地区上时,我知道如何使每个国家/地区突出显示,但我希望当我将鼠标悬停在该大陆的任何国家/地区时,我希望该大陆的所有国家/地区都突出显示。

标签: javascriptcsssvg

解决方案


那张世界地图的组织方式我可以说的不多。有作为类添加的二合字母国家代码(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;
}

推荐阅读