我正在从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,这可能是问题所在吗?
答案 0 :(得分:3)
要设置这些元素的样式,有两种方法:
向元素本身添加内联CSS。
phone.style.color = 'blue';
向元素添加一些ID或类,然后引用它们
phone.className += "my-element";
.my-element {color: blue;}
答案 1 :(得分:0)
只需添加一个className
并在CSS代码中创建该CSS类:
// Javascript
let blue = document.createElement('p');
let orange = document.createElement('p');
blue.textContent = "blue text";
orange.textContent = "orange text";
blue.className = "blue";
orange.className = "orange";
app.appendChild(blue);
app.appendChild(orange);
/* CSS */
.blue { color: blue; }
.orange { color: orange; }
<!-- HTML -->
<div id="app"></div>
答案 2 :(得分:0)
在创建的元素上使用className.add
为其分配CSS类。我已经修改了您的代码,以使所有名称都变为粗体,电话号码变为蓝色并带有下划线。
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");
// Assign a CSS class name to the element.
name.classList.add('user-name');
name.innerText = user.name.first;
document.body.appendChild(name);
const phone = document.createElement("SPAN");
phone.classList.add('phone-number');
phone.innerText = user.phone;
document.body.appendChild(phone);
console.log(user);
}
});
.user-name {
font-weight: bold;
}
.phone-number {
color: blue;
text-decoration: underline;
}