简体   繁体   English

更改所选选项的背景颜色

[英]Change the background color of the selected option

I have a select object and I'm trying to change the background color of the selected option. 我有一个选择对象,并且我正在尝试更改所选选项的背景颜色。 So when I select the option "green", the background color has to be changed to green (color information to be taken from the attribute data-color) 因此,当我选择选项“绿色”时,背景颜色必须更改为绿色(颜色信息将从属性data-color中获取)

The following works but it's not considering attribute data-color and uses just one color (red). 下面的方法有效,但它没有考虑属性data-color,而仅使用一种颜色(红色)。 I'm fine with a jQuery solution or pure CSS. 我对jQuery解决方案或纯CSS很好。

https://jsfiddle.net/tomsx/y3ofg0m7/ https://jsfiddle.net/tomsx/y3ofg0m7/

<select id="colors" size="5" style="height:80px;width:100px">
 <option value="1" data-color="red">red</option>
 <option value="2" data-color="green">green</option>
 <option value="3" data-color="yellow" >yellow</option>
</select>

select:focus option:checked {
  background: red linear-gradient(0deg, red 0%, red 100%);
}

 $("select#colors").change(function () { var $thisMenu = $(this); $thisMenu.children("option").css("background", ""); var $thisOption = $thisMenu.children("option:selected"); var color = $thisOption.data("color"); $thisOption.css("background", "linear-gradient(0deg, "+ color +" 0%, "+ color +" 100%)"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <select id="colors" class="colors2" size="5" style="height:80px;width:100px"> <option value="1" data-color="red">red</option> <option value="2" data-color="green">green</option> <option value="3" data-color="yellow" >yellow</option> </select> 

This works but it changes the colors permanently when selected. 这可以工作,但是选择后会永久更改颜色。 Is this what you want or do you want the color to be lost when another option is selected? 选择其他选项时,这是您想要的还是希望颜色丢失的?

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

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