Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - How to apply background-color to a selected option?

I'm writing a dropdown menu with several options and their colors. I have successfully colored the background of each option; however, once selected that background color doesn't show.

Is there a way to change this behavior? Example of my HTML below:

<select>
  <option style="background-color: green">Successful</option>
  <option style="background-color: orange">Process Failure</option>
  <option style="background-color: purple">Abandoned</option>
</select>

or also here: http://jsfiddle.net/H8HVm/1/.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use jQuery to read the class of the selected option then set that class as the class of the <select>. Here is the code, followed by a fiddle:

$("#color_me").change(function(){
    var color = $("option:selected", this).attr("class");
    $("#color_me").attr("class", color);
});
.green {
    background-color: green;
}
.orange {
    background-color: orange;
}
.pink {
    background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="color_me" class="">
    <option class="green">successful</option>
    <option class="orange">process failure</option>
    <option class="pink">abandoned</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...