javascript - 如何使用 CSS 为动态创建的元素设置样式

标签 javascript html css responsive

我正在尝试制作一个应用程序,它允许我在表格中添加天数

我有以下代码

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/

相关文章:

javascript 使用输入中的字符串创建日期对象

html - 如何删除 h1 标签中文本周围的默认空格

javascript - onclick 事件中的函数不起作用

html - 动态创建复选框列

css - 字体在 FF 10.0.1 中对我不起作用

javascript - 禁用按钮,直到单击一个单选按钮

javascript - 在 React + ES6 中重置初始状态

javascript - 使用转义键关闭模态的 Angular 指令

javascript - 如何将 CSS 属性设置为 if 语句中的条件?

php - 向 PHP 行添加唯一的 CSS 类