且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

下拉选择值背景色

更新时间:2023-02-22 14:19:32

<html>
<head>
<style type="text/css">
option.red {background-color:red}
option.blue {background-color:blue}
option.white {background-color:white}
</style>
</head>

<select>
<option value="item 1" class="red">Item 1</option>
<option value="item 2" class="blue">Item 2</option>
<option value="item 3" class="white">Item 3</option>
</select>
</html>



or

You''ll need some JavaScript for it to work in other browsers:

<select onchange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor"> 
    <option style="background-color:yellow">Item 1</option> 
    <option style="background-color:lightyellow">Item 2</option> 
</select> 


Even nicer with css class names:

<select>
    onchange="this.className=this.options[this.selectedIndex].className" 
    class="important"> 
    <option class="important" selected="selected">Item 1</option> 
    <option class="sorta-important">Item 2</option> 
</select> 


And your css:

.important { background-color:yellow; } 
.sorta-important { background-color:lightyellow; }