我有一个列表,在JavaScript中显示了一个附加数组,问题是我不知道如何从第一个测试色块中取出我的色块并将其附加到所有<li>
中。
我该如何解决这个问题?
这是我到目前为止的内容:
HTML:
SELECT A COLOR
<div class="dropdown-container">
<ul class="swatches" id="swatches">
<li class="cell">
COLOR 1
<div class="colorBox"></div>
<!--END COLOR BOX-->
</li>
<!--END LI-->
</ul>
<!--END SWATCHES-->
</div>
<!--END DROPDOWN CONTAINER-->
JS:
//Establish the text array
var colors = ["red", "blue", "green", "purple", "orange", "teal", "yellow"];
//loop for text name
for (var i = 0; i < colors.length; i++) {
//set color for each
var name = colors[i];
//grab the ul- swatches
var ul = document.getElementById("swatches");
//creates the new li
var li = document.createElement('li');
//appending the array to the li
li.appendChild(document.createTextNode(name));
const div = document.createElement('div');
div.className = 'colorBox';
li.appendChild(div);
//appending the li to the ul
ul.appendChild(li);
}
CSS:
body {
padding: 0;
margin: 0;
background-color: #333;
font-family: roboto;
color: white;
text-transform: uppercase;
}
.dropdown-container {
width: 80%;
height: 150px;
float: left;
background-color: #dddddd;
overflow-y: auto;
overflow-x: hidden;
}
ul.swatches {
width: 100%;
float: left;
color: #333333;
list-style-type: none;
}
ul.swatches li {
width: 80%;
height: 30px;
float: left;
border-bottom: 1px solid #333333;
margin: 0 0 10px 0;
position: relative;
padding: 0 0 0 0;
}
ul.swatches li:hover {
background-color: pink;
cursor: pointer;
}
ul.swatches li .colorBox {
width: 20px;
height: 20px;
position: absolute;
top: 0;
left: 0;
margin-left: -25px;
background-color: blue;
border-radius: 50%;
}
然后我有一个jsfiddle文件,除了一个色块外,所有文件都可以正常工作。
有任何想法吗?
https://jsfiddle.net/kotten03/xwt708Lb/228/
最佳答案
您可以尝试以下功能。它基本上将具有div
类的colorBox
添加到每个列表项。
//Establish the text array
var colors = ["red", "blue", "green", "purple", "orange", "teal", "yellow"];
//loop for text name
for (var i = 0; i < colors.length; i++) {
//set color for each
var name = colors[i];
//grab the ul- swatches
var ul = document.getElementById("swatches");
//creates the new li
var li = document.createElement('li');
//appending the array to the li
li.appendChild(document.createTextNode(name));
const div = document.createElement('div');
div.className = 'colorBox'
li.appendChild(div);
//appending the li to the ul
ul.appendChild(li);
}