我从 API 中选择数据,然后使用 document.createElement 将其制作成对象,但我该如何设置它们的样式?
这是我的 Js 代码:
fetch('https://randomuser.me/api/?results=5&nat=us').then(response =>{
return response.json();
}).then(responseJson=>{
responseJson.results
console.log(responseJson);
for(const user of responseJson.results){
const img = document.createElement ("IMG");
img.innertext = user.picture.medium;
img.setAttribute("src", user.picture.medium)
img.setAttribute("width", "50");
img.setAttribute("height", "50");
img.setAttribute("alt", "");
document.body.appendChild(img)
const name = document.createElement("SPAN");
name.innerText = user.name.first;
document.body.appendChild(name);
const phone = document.createElement("SPAN");
phone.innerText = user.phone;
document.body.appendChild(phone);
console.log(user);
}
})
我尝试引用 name.innerText 但这也没有用。但是我可以通过打电话来引用他们, 示例:
span {
color: blue;
}
当我检查代码时,它显示它创建的跨度没有任何 id,这可能是问题所在吗?
最佳答案
设置这些元素的样式有两种方式:
将内联 CSS 添加到元素本身。
phone.style.color = 'blue';
给元素添加一些ID或者类然后引用它们
phone.className += "我的元素";
.my-element {颜色:蓝色;}
关于javascript - 如何在 CSS 中引用 document.createElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52380724/