修改选择只有第一个是灰色的 [英] Modify Select So Only The First One Is Gray

查看:155
本文介绍了修改选择只有第一个是灰色的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 select 元素,并且使用第一个选项作为select字段的标题。我想知道在选择第一个选项时是否有一种方法可以将中的文本变灰,选择字段。这只能用JS完成,还是有CSS解决方案?



我试着改变第一个选项的样式,但只有当我激活下拉菜单时才会改变文本的颜色。

 < select> 
< option>请选择您喜欢的水果< / option>
< option> Apple< / option>
< option> Banana< / option>
< / select>


解决方案

September 2017 edit



您应该查看下面的 Tessa的答案,因为它只是CSS,现在好多了!这个答案现在已经差不多5年了,所以事情发生了一些变化。



原始答案



我接近你所需要的:



你需要灰色整个SELECT(当它关闭时,它是灰色的),然后un-grey所有的OPTION(把它们变成黑色)和灰色的第一个孩子。就像这样:



CSS

 选择
{
颜色:#ccc;
}
选项
{
颜色:#000;
}
选项:第一个孩子
{
颜色:#ccc;
}

编辑
So编辑过的代码是:



HTML

 < select onchange =changeMe(this)> 
<选项已禁用>请选择您喜欢的水果< / option>
< option> Apple< / option>
< option> Banana< / option>
< / select>

Javascript

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

我更新了jsFiddle。你可以在这里查看: http://jsfiddle.net/s5Xy2/5/


请注意,我也更改了HTML部分,因为我认为您想使用disabled属性(因此,您必须添加selected属性也是如此)。

如果你仍然想要纯粹的CSS代码,它在这里: http://jsfiddle.net/s5Xy2/4/


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>

解决方案

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/

这篇关于修改选择只有第一个是灰色的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆