gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:03:26 26 4
gpt4 key购买 nike

我想从事件监听器重置颜色,因此当单击下一个元素时,颜色将从上一个元素重置。

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,然后在再次循环之前重置它,但我的解决方案只是完全破坏了我的获取。

最佳答案

您可以使用 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>

关于javascript - 单击下一个元素时重置颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com