如何根据接收到的数据改变类的颜色?



Ok,所以我正在制作随机poksammon生成器,每次用户单击生成按钮时,它都会选择1-905(National Dex中的poksammon数量)之间的随机数。我能够显示生成的poksammon的图像、名称/id和类型。我卡住的是如何根据输入的pok录影带来改变显示pok录影带的容器/类的背景颜色。假设pok郁闷的输入是草,我希望背景是绿色。我真的不知道从哪里开始。

我正在使用PokeApi

const pokemongenerated = document.getElementById('pokemongenerated');
const fetchPokemon = () => {
const array = [];
const randomID = Math.floor(Math.random() * 906) + 1;

const url = `https://pokeapi.co/api/v2/pokemon/${randomID}`;
array.push(fetch(url).then((res) => res.json()));
Promise.all(array).then((results) => {
const pokemon = results.map((data) => ({
name: data.name,
image: data.sprites['front_default'],
type: data.types.map((type) => type.type.name).join(', '),
id: data.id,


}));
displayPokemon(pokemon);
});
};
const displayPokemon = (pokemon) => {
console.log(pokemon);
const pokemonHTMLString = pokemon
.map(
(pokemon) => `
<ul class="card">
<img class="card-image" src="${pokemon.image}"/>
<h2 class="card-name"> ${pokemon.id}. ${pokemon.name}</h2>
<p class="card-type">Type: ${pokemon.type}</p>
</ul>
`
)
.join('');
pokemonGenerated.innerHTML = pokemonHTMLString;
};
fetchPokemon();

1。在对象上创建typeCss2.为所有类型的

设置css样式

const pokemongenerated = document.getElementById('pokemongenerated');
const fetchPokemon = () => {
const array = [];
const randomID = Math.floor(Math.random() * 906) + 1;

const url = `https://pokeapi.co/api/v2/pokemon/${randomID}`;
array.push(fetch(url).then((res) => res.json()));
Promise.all(array).then((results) => {
const pokemon = results.map((data) => ({
name: data.name,
image: data.sprites['front_default'],
type: data.types.map((type) => type.type.name).join(', '),
typeCss: data.types.map((type)=>type.type.name).join('--'),
id: data.id,


}));
displayPokemon(pokemon);
});
};
const displayPokemon = (pokemon) => {
console.log(pokemon);
const pokemonHTMLString = pokemon
.map(
(pokemon) => `
<ul class="card pokemon-type type-${pokemon.typeCss}">
<img class="card-image" src="${pokemon.image}"/>
<h2 class="card-name"> ${pokemon.id}. ${pokemon.name}</h2>
<p class="card-type">Type: ${pokemon.type}</p>
</ul>
`
)
.join('');
document.querySelector('#pokemonGenerated').innerHTML = pokemonHTMLString;
};
fetchPokemon();
.pokemon-type[class*="water"]{
background:blue;
}
.pokemon-type[class*="grass"]{
background:green;
}
//so on
<div id="pokemonGenerated"></div>

相关内容

  • 没有找到相关文章

最新更新