选择选项html内的颜色框

时间:2018-12-08 07:12:36

标签: javascript html css

HTML中选择选项内的

颜色框 我想使用html和css而不使用jquery或javascript Output should be like this

我尝试过

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #f1f1f1
}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}
<h2>Dropdown Menu</h2>

<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#"><span style="background-color:Red">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    Red</a>
    <a href="#"> <span style="background-color:Green">&nbsp;&nbsp;&nbsp;&nbsp;</span> Green
    </a>
  </div>
</div>


<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <span class="color" style="background-color:Red">&nbsp;&nbsp;&nbsp;&nbsp;</span> Red
    <span class="color" style="background-color:Green">&nbsp;&nbsp;&nbsp;&nbsp;</span> Green
  </div>
</div>

,但输出应在下拉列表中显示颜色框。 选择选项html内的颜色框

在这里,我在编写的代码中使用了定位标记和div标签。 但是我想要它在选择标签中

2 个答案:

答案 0 :(得分:1)

没有JavaScript就无法做到-以下是一些非常简单的点击处理程序,可以满足您的需求:

function updateColor(element) {
    var newColor = element.firstChild.style.backgroundColor;
    element.parentElement.parentElement.style.backgroundColor = newColor;
    console.log(newColor);
}
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #f1f1f1
}

.dropdown:hover .dropdown-content {
  display: block;
}

.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}
<h2>Dropdown Menu</h2>

<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#" onclick="updateColor(this)"><span style="background-color:Red" onclick="updateColor(this)">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    Red</a>
    <a href="#" onclick="updateColor(this)"><span style="background-color:Green">&nbsp;&nbsp;&nbsp;&nbsp;</span> Green
    </a>
  </div>
</div>


<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <div onclick="updateColor(this)"><span class="color" style="background-color:Red">&nbsp;&nbsp;&nbsp;&nbsp;</span> Red</div>
    <div onclick="updateColor(this)"><span class="color" style="background-color:Green" onclick="updateColor(this)">&nbsp;&nbsp;&nbsp;&nbsp;</span> Green</div>
  </div>
</div>

答案 1 :(得分:0)

删除“最小宽度:160像素;”来自.dropdown-content

还有

删除“填充:12px 16px;”来自.dropdown-content a