Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - Modify Select So Only The First One Is Gray

I have a select element and am using the first option as the title of the select field. I am wondering if there is a way to gray out the text inside the select field when the first option is selected. Can this only be done in JS, or is there a CSS solution?

I have tried changing the style of the first option but that only changes the colour of the text when I activate the dropdown menu.

<select>
  <option>Please select your favourite fruit</option>
  <option>Apple</option>
  <option>Banana</option>
</select>
question from:https://stackoverflow.com/questions/13694271/modify-select-so-only-the-first-one-is-gray

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

1 Answer

0 votes
by (71.8m points)

September 2017 edit

You should take a look at Tessa's answer below, since it's CSS only and much better now! This answer is almost 5 years old now, so things have changed a bit. I'm keeping the original answer just for reference.

Original answer

I am closer to what you need:

You need to gray the entire SELECT (so that when it's closed, it is gray), then "un-gray" all the OPTION's (put them black) and gray the first-child. Something like this:

CSS

select
{
    color: #ccc;
}
option
{
    color: #000;
}
option:first-child
{
    color: #ccc;
}

EDIT So the edited code is:

HTML

<select onchange="changeMe(this)">
  <option selected disabled>Please select your favourite fruit</option>
  <option>Apple</option>
  <option>Banana</option>
</select>

Javascript

<script type="text/javascript">
    function changeMe(sel)
    {
      sel.style.color = "#000";              
    }
</script>

I've update jsFiddle. You can check it here: http://jsfiddle.net/s5Xy2/5/ ?

Notice that I've also changed the HTML part, because I think you want to use the "disabled" attribute (and because of that, you'll have to add the "selected" attribute also).

If you still want the pure CSS code, it's here: http://jsfiddle.net/s5Xy2/4/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...