使用CSS为动态创建的元素设置样式
问题说明
我正在尝试制作一个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.
正确答案
您可以创建一个类并将该类添加到已创建的要素中.
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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22