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
358 views
in Technique[技术] by (71.8m points)

javascript - html select with different background color for every option that works properly in every browser?

I am looking to build multiple html select elements with custom background colors for each option:

<select runat="server" id="select">
<option value="A">White</option>
<option value="B">Red</option>
<option value="C">Yellow</option>
<option value="D">Green</option>

When the website loads, I would like the select element to display only the background color and no text for the selected option. The text (white, red,....) should only be visible when the dropdown is opened.

As the selected value is changed by the user, the background color should change as well while the text should be invisible in the closed dropdown.

It would be really nice if the solution works on most browsers including IE 9/10.

Cheers.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try this code, works in every browser including IE:

html

<select id="select1" onchange="colourFunction()">
<option class="white" value="A">This should have a WHITE background</option>
<option class="red" value="B">This should have a RED background</option>
<option class="yellow" value="C">This should have a YELLOW background</option>
<option class="green" value="D">This should have a GREEN background</option>
</select>

css

#select1 {width:150px; color:rgba(0, 0, 0, 0);}
#select1:focus, #select1:focus {
color:black;
}
.white {background:white;}
.red {background:red;}
.yellow {background:yellow;}
.green {background:green}

js

function colourFunction() {
var myselect = document.getElementById("select1"),
colour = myselect.options[myselect.selectedIndex].className;
myselect.className = colour;
myselect.blur(); //This just unselects the select list without having to click
somewhere else on the page
}

HTH :)


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

...