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>

关于JavaScript。点击一个变色,点击另一个恢复,元素很多,怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60790770/

相关文章:

Javascript:如何将动态键插入 map /对象?

javascript - 有没有办法让更新功能更快

javascript - 一个字符一个字符地删除

javascript - 无限水平滚动动画的问题

javascript - Ionic 框架中使用 Translate 的 AngularJS 菜单

javascript - Angular 4 刷新 <img src={{ ... }} > 当值改变时

javascript - 选中/取消选中 parent 和 child

javascript - JQuery 获取连续的元素序列

javascript - 如何让 Css-Only 灯箱在单个页面上处理多个图像?

javascript - 无法通过 Node.js 中的 Sequelize 从数据库中选择数据