foo*_*.ar 4 html css jquery-select2 twitter-bootstrap-3
我正在使用 select2 下拉菜单,并希望为每个选项设置不同的颜色。
例子:
<select class="select2" name="fruit">
<option class="red-option">Apple</option>
<option class="green-option">Kiwi</option>
<option class="blue-option">Grape</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我可以为渲染的选定选项着色,如下所示:
.select2-selection__rendered[title="Apple"] {
color: red !important;
}
Run Code Online (Sandbox Code Playgroud)
如何还为 select2 下拉列表中的选项着色 - 基于选项类('red-option')或值('Apple')?
PS:我使用 bootstrap 3.3 + jQuery,如果必须的话,不介意使用 JS 来执行此操作。
UnL*_*oCo 14
我使用选项找到了更好的解决方案
function formatState(state) {
const option = $(state.element);
const color = option.data("color");
if (!color) {
return state.text;
}
return $(`<span style="color: ${color}">${state.text}</span>`);
};
jQuery(node).select2({
templateResult: formatState,
templateSelection: formatState,
});
Run Code Online (Sandbox Code Playgroud)
在我的例子中,颜色来自 html 数据属性
<option style="color: #F00" data-color="#F00" value="1">Red Option</option>
Run Code Online (Sandbox Code Playgroud)
知道了。
Select2 使用 parentselect的属性为所有下拉选项生成一个 idname属性。
在我的示例中,我能够使用 :nth-child(x) 应用颜色,如下所示:
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(1) {
color: red;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(2) {
color: green;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(3) {
color: blue;
}Run Code Online (Sandbox Code Playgroud)
<select class="select2" name="fruit">
<option class="red-option">Apple</option>
<option class="green-option">Kiwi</option>
<option class="blue-option">Grape</option>
</select>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10315 次 |
| 最近记录: |