我正在尝试使用Javascript添加许多框。但是,与其添加多个框,不如替换第一个框。理想情况下,我想像这样工作:(1)单击“下一步”生成颜色(2)单击“保存”,这将在下面创建一个框并显示所选的颜色(3)重复,并在保留先前颜色的同时创建一个新框盒子
HTML:
<div id="displayColor"></div>
<div id="container">
<div id="controls">
<button id="previousColor">Previous</button>
<span id="saveColor"><button>Save Color</button></span>
<button id="nextColor">Next</button>
</div>
<p>Saved Colors</p>
<div class="savedColorBoxes"></div>
<script type="text/javascript" src="colorPicker.js"></script>
</body>
</html>
Javascript:
var colorDisplay = document.getElementById("displayColor");
var nextButton = document.getElementById("nextColor");
var saveButton = document.getElementById("saveColor");
var storedColors = []
var addNewBox = document.getElementsByClassName("savedColorBoxes")
nextButton.addEventListener("click", function(){
currentColor = randomColor()
displayColor.style.background = currentColor;
storedColors.push(randomColor());
return currentColor
});
saveButton.addEventListener("click", function(){
for(i = 0; i < addNewBox.length; i++){
// Add Box
addNewBox[i].classList.add("savedColorsBox")
// Update Color of the box to chosen
addNewBox[i].style.background = currentColor
}
});
function randomColor(){
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//pick a "green" from 0 -255
var g = Math.floor(Math.random() * 256);
//pick a "blue" from 0 -255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
CSS:
body {
margin: 0;
background-color: black;
}
h1 {
text-align: center;
color: white;
}
#displayColor {
height: 420px;
background-color: rgb(232, 50, 120);
margin: 0 auto;
}
#container {
margin: 0 auto;
margin-bottom: 83.88px;
text-align: center;
background-color: white;
height: 79.88px;
border: 2px solid white;
}
/*button {
border: none;
background: none;
outline: none;
font-size: 1.0em;
}*/
#controls {
margin-top: 29.44px;
}
#nextColor {
margin-left: 200px;
}
#previousColor {
margin-right: 200px;
}
#saveColor {
text-align: center;
}
.savedColorsBox {
height: 100px;
width: 70%;
margin: 0 auto;
margin-top: 20px;
background: yellow;
}
p {
margin-top: 5%;
margin-left: 15%;
width: 102.3px;
letter-spacing: 1px;
font-weight: 800;
border-bottom: 1px solid;
color: white;
}
.currentColor {
background: black;
}
答案 0 :(得分:1)
只需使用appendChild
方法将新节点添加到特定的颜色框容器中即可。
saveButton.addEventListener("click", function(){
// new node
var colorBox = document.createElement('div');
// color
colorBox.style.background = currentColor;
// append into box container
boxContainer.appendChild(colorBox);
});
在此处查看完整示例-JSFiddle