我正在尝试制作一个应用程序,它允许我在表格中添加天数
我有以下代码
function addDay() {
for (k = 1; k < 11; k++) {
let div = document.createElement("div");
div.style.background = "red"
div.style.color = "white"
div.style.width = "40px"
div.style.height = "20px"
div.style.margin = "0.5px"
div.style.textAlign = "center"
div.style.borderRadius = "6px"
div.setAttribute("class", "studentGrades")
// div.setAttribute("class", "sgID" + k)
div.className += " sgID" + k
div.setAttribute("onclick", "averageFunc(this, Number(prompt('Please, enter number here')))");
div.innerHTML = "0"
document.querySelector("#container3").appendChild(div)
}}
这对我来说非常好,但我还必须为这个应用程序做一个响应式设计,所以在较小的屏幕上,
这些属性太大了,
div.style.width = "40px"
div.style.height = "20px"
我需要类似的东西,
div.style.width = "20px"
div.style.height = "10px"
问题来了,这些元素是动态创建的,加载 HTML 时它们不存在,所以我不能用 CSS 设置它们的样式,是否可以通过 CSS 设置这些元素的样式?如果是的话怎么办?
This is on a big screen, Add day button adds 1 green and 10 red boxes
Same here, except i want those boxes to be smaller (same size as the boxes next to it)
附言
我的编码冒险已经进入第 3 周,我只熟悉 Vanilla JS,所以没有库/框架。
最佳答案
您可以创建一个类并将该类添加到创建的元素中。
例子:
for (k = 1; k < 11; k++) {
let div = document.createElement("div");
div.setAttribute("onclick", "averageFunc(this, Number(prompt('Please, enter number here')))");
div.className = 'custom-class';
div.innerHTML = "0"
document.getElementById("container3").appendChild(div)
}
.custom-class {
background : red;
color: white;
width : 20px;
height : 20px;
margin-top :2px;
text-align : center;
border : 1px solid black;
}
<div id="container3"></div>
关于javascript - 如何使用 CSS 为动态创建的元素设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51327671/