javascript - 根据变量显示多个 div
问题描述
如何动态打印 N 个 div(每个 div 代表一个点)?我是 HTML 和 CSS 的新手,有没有办法根据变量打印 N 个 div。我需要一个 Jquery 函数吗?
.dot-container {
display: inline-block;
}
.dot{
width:10px !important;
height:10px !important;
border-radius: 50%;
display: inline-block;
}
.red{
background-color: red !important;
}
.blue{
background-color: blue !important;
}
.yellow{
background-color: yellow !important;
}
<div class="dot-container">
<div class="dot red"></div>
<div class="dot blue"></div>
<div class="dot yellow"></div>
<div class="dot red"></div>
</div>
解决方案
你可以用 JS 来做。输入一个数字并单击创建按钮:
let button = document.getElementById("button")
, number = document.getElementById("number")
, ctn = document.getElementById("dot-container")
// Just a function to add random colors
, getRandomColor = function() {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
button.addEventListener("click", () => {
for(let i = 0; i < Number(number.value); i++){
let dot = document.createElement("div");
dot.classList.add("dot")
dot.style.backgroundColor = getRandomColor();
ctn.appendChild(dot)
}
})
.dot {
width: 10px !important;
height: 10px !important;
border-radius: 50%;
display: inline-block;
margin-right: 5px;
}
<input type="number" id="number" />
<button id="button">Create</button><br/><br/>
<div id="dot-container">
</div>
推荐阅读
- angular - 仅删除 mat-select 组件的 Scroll Webkit css 类
- go - cmd找不到文件
- css - jekyll 中的 CSS 覆盖
- typescript - 在 nestjs 中导入并注入 typeorm 存储库
- c - 在 C 中检测矩阵中的岛
- telegram - 有没有办法在电报中找到具有频道 ID 的私人频道
- reactjs - MUIDataTable 不使用 customBodyRender 对列进行排序
- mule - 骡 SQL Server 2012 到 SSAS
- pipe - 使用 GNU 并行 (samtools) 的管道命令
- r - 使用 R 解析具有多个节点集的 XML