首页 > 解决方案 > 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。

如果元素(国家)是三个或五个,我可以这样做,但是元素太多,有没有一种紧凑的方法来获得这种效果?

感谢您的关注,如果可以,请帮助我。:)

标签: javascript

解决方案


您可以在单击时取消选择所有元素,然后选择被单击的元素:

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>


推荐阅读