单击下一个元素时重置颜色

时间:2019-03-09 21:17:39

标签: javascript dom svg

我想从eventListener中重置颜色,所以当单击下一个元素时,颜色将从上一个元素重置。

import "bootstrap/dist/css/bootstrap.css";

const root = document.getElementById("root");
var tbody = document.getElementById("tbody");
var svg = document.getElementById("svg");

const country = "https://restcountries.eu/rest/v1/alpha?codes=";

var resetColor;

svg.addEventListener("load", function() {
  var svgDoc = svg.contentDocument;

  [...svgDoc.querySelectorAll("path")].forEach(path => {
    path.addEventListener("click", e => {
      getCountryNew(path.id);
      path.style.fill = "#ff9900";
    });
  });
});

function getCountryNew(landcode) {
  fetch(country + landcode)
    .then(res => res.json())
    .then(countries => {
      var c = countries.map(country => {
        return (
          "<tr>" +
          "<td>" +
          country.name +
          "</td>" +
          "<td>" +
          country.capital +
          "</td>" +
          "<td>" +
          country.altSpellings +
          "</td>" +
          "<td>" +
          country.region +
          "</td>" +
          "<td>" +
          country.population +
          "</td>" +
          "<td>" +
          country.languages +
          "</td>"
        );
      });
      tbody.innerHTML = c;
    });
}

我假设我必须保存路径ID,然后在循环之前再次将其重置,但是我的解决方案仅破坏了我的获取。

1 个答案:

答案 0 :(得分:1)

您可以使用CSS为内嵌svg 着色,因此,要更改/重置颜色,需要在元素中添加/删除类。

使用:last-child为最后一个svg图标着色的小示例。

const svg = `<svg aria-hidden="true" focusable="false" data-prefix="fab" data-icon="font-awesome-flag" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" class="color-inherit svg-inline--fa fa-font-awesome-flag fa-w-14 fa-fw" style="transform-origin: 0.4375em 0.5em;"><g transform="translate(224 256)" class=""><g transform="translate(0, 0)  scale(0.5625, 0.5625)  rotate(0 0 0)" class=""><path fill="currentColor" d="M444.373 359.424c0 7.168-6.144 10.24-13.312 13.312-28.672 12.288-59.392 23.552-92.16 23.552-46.08 0-67.584-28.672-122.88-28.672-39.936 0-81.92 14.336-115.712 29.696-2.048 1.024-4.096 1.024-6.144 2.048v77.824c0 21.405-16.122 34.816-33.792 34.816-19.456 0-34.816-15.36-34.816-34.816V102.4C12.245 92.16 3.029 75.776 3.029 57.344 3.029 25.6 28.629 0 60.373 0s57.344 25.6 57.344 57.344c0 18.432-8.192 34.816-22.528 45.056v31.744c4.124-1.374 58.768-28.672 114.688-28.672 65.27 0 97.676 27.648 126.976 27.648 38.912 0 81.92-27.648 92.16-27.648 8.192 0 15.36 6.144 15.36 13.312v240.64z" transform="translate(-224 -256)" class=""></path></g></g></svg>`;
const $root = document.getElementById('root');

function addIcon() {
  $root.innerHTML += svg;
}
svg {
  width: 50px;
}

#root svg:last-child path {
  fill: red;
}
<div id="root"></div>

<button onclick="addIcon()">+</button>