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