我正在尝试为使用JavaScript创建的元素设置样式:
const h1 = document.createElement("h1");
h1.textContent = data.name;
h1.setAttribute("id", "heading");
window.data.appendChild(h1);
这是我的CSS代码:
#heading{
padding-right: 100px;
colour: red;
}
该元素出现在页面上,因为我有一个异步函数,该函数从JSON文件中获取数据,但是我看不出该元素的样式有所不同。由于我也是JavaScript的新手,因此我似乎在代码中找不到问题。
答案 0 :(得分:1)
类似这样的东西应该可以工作:
h1.style.color = "red";
h1.style.paddingRight = "100px";
查看文档以了解其他特定情况 https://www.w3schools.com/jsref/dom_obj_style.asp
此外,CSS中的一个好习惯是避免使用 id 定位元素。如果可能,请直接使用HTML标记,或者类别
以您的情况代替
h1.setAttribute("id", "heading");
您应该
h1.classList.add("heading");
然后在您的CSS中显示(如果需要)
.heading{
padding-right: 100px;
colour: red;
}
答案 1 :(得分:1)
color
而不是colour
。
window.data
未定义
const h1 = document.createElement("h1");
h1.textContent = data.name;
h1.setAttribute("id", "heading");
document.getElementById("content").appendChild(h1);