首页 > 解决方案 > 根据变量显示多个 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>

那是我的代码:https ://jsfiddle.net/bpc8shra/

标签: javascriptjqueryhtmlcss

解决方案


你可以用 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>


推荐阅读