[英]DOM style property in Js
js 初学者。 我正在使用 pokeapi 创建一个 pokedex,并希望使用 js 中的 .style 根据存储在对象中的类型使用颜色更改 pokecards 的背景
目前我已经编写了这段代码
const typecolor = {
bug: "#26de81",
dragon: "#ffeaa7",
electric: "#fed330",
fairy: "#FF0069",
fighting: "#30336b",
fire: "#f0932b",
flying: "#81ecec",
grass: "#00b894",
ground: "#EFB549",
ghost: "#a55eea",
ice: "#74b9ff",
normal: "#95afc0",
poison: "#6c5ce7",
psychic: "#a29bfe",
rock: "#2d3436",
water: "#0190FF",
};
const abilities = document.querySelector(".power1 p");//ptag inside pokecard
function generatehtml(result) {
const card = document.createElement("div");
card.classList.add("pokecard");
let newhtml = `
<div class=pokecard>
.
.
.
</div>`
themecolor = typecolor[result.types[0].type.name]; //getting poketype from api
card.style.background = `radial-gradient(circle at 50% 0%, ${themecolor} 36%, #ffffff 36%)`;
abilities.style.backgroundColor = `${themecolor}`;//a <p> tag to be colored
}
虽然主题颜色被控制台注销,但没有明显的变化工作版本: https ://megahedron69.github.io/Pokedex/js 文件: https : //github.com/Megahedron69/Pokedex/blob/main/app.js
创建卡片元素但不附加到 dom 的第一件事。
其次,您正在尝试获取 element const abilities = document.querySelector(".power1 p");
这在 DOM 中不存在。
为什么不在创建卡片 DOM 时向 HTML 本身添加样式。
优化代码
function generatehtml(result, appendToList) {
const themecolor = typecolor[result.types[0].type.name];
const name = result.name[0].toUpperCase() + result.name.slice(1);
const newhtml = `
<div class=pokecard style="background: radial-gradient(circle at 50% 0%, ${themecolor} 36%, #ffffff 36%)">
.
.
.
<div class="power1">
<p style="background: ${themecolor}">
${result.types[0].type.name}
<img src="Grass.png" />
</p>
</div>
.
.
.
</div>
`;
if (appendToList)
searchcont.innerHTML += newhtml;
else
searchcont.innerHTML = newhtml;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.