我正在尝试制作一个APP,这使我可以在表格中添加天数

我有以下代码

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)

压力

我进入编码冒险的第三周,我只熟悉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>

07-25 21:55
查看更多