我如何将色块附加到我的li列表上?

问题描述 投票:0回答:1

[我有一个列表,在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/

javascript arrays loops append html-lists
1个回答
1
投票

您可以尝试以下代码段。基本上,将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);
  }
© www.soinside.com 2019 - 2024. All rights reserved.