是否可以仅更改select元素中第一个选项的字体颜色

时间:2016-06-06 10:24:19

标签: javascript jquery html css

使用Select2js插件,是否可以仅更改select元素中第一个选项的字体颜色?

我试过......

select option:first-child { color:red; }

$(function() {
    $("select option:first-child").addClass("red");
});

.red { color:red; }

示例:

$(function() {
    $("select").select2();
  $("select option:first-child").addClass("red");
});
.red {color: red;}
select option:first-child {color: red;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<select>
  <option>Text 1</option>
  <option>Text 2</option>
  <option>Text 3</option>
</select>

1 个答案:

答案 0 :(得分:3)

如果右键单击select2选项并选择&#34; Inspect&#34; (或&#34; Inspect Element&#34;,具体取决于您的浏览器),您会发现他们不是option元素,他们是li元素select2-results__option中的班级ul,班级为select2-results__options

所以:

.select2-results__options li.select2-results__option:first-child {
  color: red;
}

Updated Fiddle,或作为Stack Snippet:

&#13;
&#13;
$(function() {
  $("select").select2();
  $("select option:first-child").addClass("red");
});
&#13;
.select2-results__options li.select2-results__option:first-child {
  color: red;
}
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select>
  <option>Text 1</option>
  <option>Text 2</option>
  <option>Text 3</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
&#13;
&#13;
&#13;

如果您愿意,可以使用类select2-results__option--highlighted进一步细化活动元素的样式,该类在元素处于活动状态时添加。&#34;例如,在这里,当它不活动时我把它变成了蓝色,当它是:时它是红色的:

&#13;
&#13;
$(function() {
  $("select").select2();
  $("select option:first-child").addClass("red");
});
&#13;
.select2-results__options li.select2-results__option:first-child {
  color: blue;
}
.select2-results__options li.select2-results__option.select2-results__option--highlighted:first-child {
  color: red;
}
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<select>
  <option>Text 1</option>
  <option>Text 2</option>
  <option>Text 3</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
&#13;
&#13;
&#13;