javascript - JavaScript。点击一个改变颜色,点击另一个恢复,很多元素,怎么做?
问题描述
我试图给 .svg 世界地图一个 JavaScript“点击更改颜色”功能。
预期行为:
单击一个国家更改其颜色,单击另一个国家更改颜色,但之前单击恢复为默认颜色。
我现在的错误:
单击一个国家,它的颜色改变了,但单击另一个,以前的颜色保持不变。
有错误的代码(意外):
svg结构:
<g name="us"><path>...</path></g>
<g name="au"><path>...</path></g>
<g name="es"><path>...</path></g>
.....
<g name="ca"><path>...</path></g>
JavaScript 部分:
(function () {
var world = document.getElementById("world"); // The svg file
world.addEventListener("load", function () {
var doc = world.getSVGDocument();
doc.addEventListener("click", function (e) {
e.preventDefault();
var target = e.target,
target.style.fill = "#eee";
});
});
}());
需要纯 JavaScript,不需要 jQuery。
如果元素(国家)是三个或五个,我可以这样做,但是元素太多,有没有一种紧凑的方法来获得这种效果?
感谢您的关注,如果可以,请帮助我。:)
解决方案
您可以在单击时取消选择所有元素,然后选择被单击的元素:
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>
推荐阅读
- opencv - 如何在二维图像上显示已知 CAD 模型的方向?
- r - 是什么决定了 ggplot2 对象中“flipped_aes”的出现?
- python - 带有 matplotlib 的 Pyinstaller(conda 环境)
- docker - Docker Swarm 节点 IP 地址作为环境变量
- ansible - Ansible-playbook 永远挂起 - vmware_vm_shell
- python - 查找最大化某些功能的值的字典键
- r - 使用带有 R 中条件的最后两个日期计算时间
- flutter - 我想自定义验证后显示的错误文本
- python - DataFrame 列中的嵌套列表:如何对单个值进行计算?
- listview - Xamarin 将 ListView 绑定到静态资源可观察集合