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。


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


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


慕村225694
浏览 326回答 1
1回答

紫衣仙女

您可以在单击时取消选择所有元素,然后选择被单击的元素:const svg = document.getElementById('world');const elements = svg.getElementsByTagName('g');svg.onclick = ({ target }) => {&nbsp; // make sure we clicked on a group or a child of one&nbsp; // and do nothing if we havent&nbsp; const g = target.closest('g');&nbsp;&nbsp; if (!g) return;&nbsp;&nbsp;&nbsp; // remove selected class from all&nbsp; // and add it to the one clicked&nbsp; [...elements].forEach(e => e.classList.remove('selected'));&nbsp; g.classList.add('selected');};.selected {&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript