如何在hover页面其他元素时修改SVG地图路径的填充样式?
问题原因说明
你当前写的CSS无法生效,是因为~兄弟选择器仅支持匹配同一个父元素下、位于当前元素后方的同级节点,而你的触发元素.chateauneufbeta在侧边城市列表容器内,目标元素.maptest在SVG地图容器内,二者不属于同一个父级,CSS没有能力跨父级匹配元素,因此该需求无法通过纯CSS实现,只需要加少量JavaScript代码即可实现效果,对JS基础要求很低。
实现代码
仅适配Châteauneuf单个城市的代码
把下面的代码添加到Wordpress站点的自定义JS区块即可生效:
document.addEventListener('DOMContentLoaded', function() { const trigger = document.querySelector('.chateauneufbeta'); const targetMap = document.querySelector('.maptest'); // 鼠标移入时高亮地图 trigger.addEventListener('mouseenter', () => { targetMap.style.fill = '#93c020'; targetMap.style.opacity = '1'; }); // 鼠标移出时恢复默认样式 trigger.addEventListener('mouseleave', () => { targetMap.style.fill = ''; targetMap.style.opacity = ''; }); });
适配所有城市的通用代码
如果后续要给所有城市都加hover联动效果,不需要重复写代码,只需要先给SVG中每个地图路径节点加上和侧边列表对应一致的data-area-id属性,再用下面的代码即可批量绑定所有城市的联动效果:
document.addEventListener('DOMContentLoaded', function() { const allCityLinks = document.querySelectorAll('.location__list-link'); allCityLinks.forEach(link => { const areaId = link.dataset.areaId; const targetArea = document.querySelector(`path[data-area-id="${areaId}"]`); if(!targetArea) return; link.addEventListener('mouseenter', () => { targetArea.style.fill = '#93c020'; targetArea.style.opacity = '1'; }); link.addEventListener('mouseleave', () => { targetArea.style.fill = ''; targetArea.style.opacity = ''; }); }); });
Wordpress添加方法
登录站点后台,依次进入「外观」-「自定义」-「自定义CSS/JS」,把代码粘贴到自定义JS输入框中,保存设置即可生效。
内容的提问来源于stack exchange,提问作者Croquix
相关产品推荐
相关产品推荐

