• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

使用CSS为动态创建的元素设置样式

用户头像
it1352
帮助1

问题说明

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

I'm trying to make an APP, which allows me to add days to a table

我有以下代码

function addDay() {

for (k = 1; k < 11; k  ) {
    let div = document.createElement("div");
    div.style.background = "red"
    div.style.color = "white"
    div.style. 
    div.style. 
    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)
}} 

这对我来说很好用,但是我还必须为此应用程序设计一个响应式设计,所以在较小的屏幕上,

This works perfectly fine for me, But I also have to make a Responsive design for this app, so on a smaller screen,

这些属性太大,

    div.style. 
    div.style. 

我需要类似的东西,

    div.style. 
    div.style. 

这就是问题所在,这些元素是动态创建的,在加载HTML时不存在,因此我无法使用CSS设置样式,是否可以通过CSS设置这些元素的样式?如果是的话,怎么办?

So here is the problem, These elements are dynamically created, They are not present when HTML is loaded, So I can't style them with CSS, Is it Possible to style those elements via CSS? And if yes how?

这是一个大屏幕,添加日期"按钮会添加1个绿色框和10个红色框

与此处相同,但我希望这些框较小(与旁边的框相同))

PS

我进入了编码冒险的第三周,我只熟悉Vanilla JS,所以不熟悉图书馆/框架.

I'm into a 3rd week of my coding adventure, I'm familiar with only Vanilla JS, So no Library/Framework's.

正确答案

#1

您可以创建一个类并将该类添加到已创建的要素中.

You can make a class and add that class to created elemets.

示例:

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>

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcggfkk
系列文章
更多 icon
同类精品
更多 icon
继续加载