【发布时间】:2020-03-01 00:30:32
【问题描述】:
我有一个在 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 文件,该文件除了色块外一切正常。 有什么想法吗?
【问题讨论】:
标签: javascript arrays loops append html-lists