1 回答

TA贡献1839条经验 获得超15个赞
您可以在单击时取消选择所有元素,然后选择被单击的元素:
const svg = document.getElementById('world');
const elements = svg.getElementsByTagName('g');
svg.onclick = ({ target }) => {
// make sure we clicked on a group or a child of one
// and do nothing if we havent
const g = target.closest('g');
if (!g) return;
// remove selected class from all
// and add it to the one clicked
[...elements].forEach(e => e.classList.remove('selected'));
g.classList.add('selected');
};
.selected {
fill: yellow;
}
<svg id="world" width="100" height="100" viewBox="0 0 30 30">
<g data-country="1"><rect x="0" y="0" width="10" height="10"/></g>
<g data-country="2"><rect x="10" y="10" width="10" height="10"/></g>
<g data-country="3"><rect x="20" y="20" width="10" height="10"/></g>
<g data-country="4"><rect x="0" y="20" width="10" height="10"/></g>
</svg>
添加回答
举报