简体   繁体   English

css 将所选选项的背景颜色设置为选择标签的背景

[英]Css set background-color of the selected option to the background of select-tag

The different options of the html select form field show the correct 'colors' of my options as the background-color. html 选择表单字段的不同选项将我的选项的正确“颜色”显示为背景颜色。

But when one option is selected and thus the select element is shown 'collapsed' it shows a default white background. But when one option is selected and thus the select element is shown 'collapsed' it shows a default white background.

What is a clean way to update the background of the select box to the one of the option ?将选择框的背景更新为选项之一的干净方法是什么?

 <select> <option style="background-color: #CDBA88">RAL:1000</option> <option style="background-color: #D0B084">RAL:1001</option> <option style="background-color: #D2AA6D">RAL:1002</option> <option style="background-color: #F9A800">RAL:1003</option> <option style="background-color: #E49E00">RAL:1004</option> </select>

You have to use Javascript as well.您还必须使用 Javascript。 So, in a nutshell, on onchange event, you have to assign a function that sets background color to <select> component.因此,简而言之,在onchange事件中,您必须分配一个将背景颜色设置为<select>组件的函数。

Here is a working snippet of what I mean:这是我的意思的一个工作片段:

 var selectBox = document.getElementById('select-box'); function applyBackgroundColor() { // Check if DOM element exists, otherwise return if (!selectBox) { return; } selectBox.style.backgroundColor = selectBox.value; } selectBox.onchange = applyBackgroundColor;
 <select id="select-box"> <option value="#cdba88" style="background-color: #cdba88">RAL:1000</option> <option value="#d0b084" style="background-color: #d0b084">RAL:1001</option> <option value="#d2aa6d" style="background-color: #d2aa6d">RAL:1002</option> <option value="#f9a800" style="background-color: #f9a800">RAL:1003</option> <option value="#e49e00" style="background-color: #e49e00">RAL:1004</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM