![](/img/trans.png)
[英]Change the background color of an <option> with JavaScript
[英]How to change the css background color of dropdown option on changing/selecting a option using javascript?
這里有下拉菜單:
<select name="sourcesSelect" id="{{this.commonID}}" class="custom-select sources" data-color="" placeholder="{{this.status}}">
<option value="0">In Progress</option>
<option value="1">Done</option>
<option value="2">Rejected</option>
</select>
默認情況下,這是 select 菜單的 css:
.custom-select-trigger {
position: relative;
display: block;
width: 280px;
padding: 0 64px 0 20px;
font-size: 16px;
font-weight: 300;
color: #fff;
line-height: 30px;
background: #265a88;
border-radius: 4px;
cursor: pointer;
}
我想要的:當我選擇選項 0 時,下拉菜單顏色將更改為綠色。 對於選項 1,它應更改為紅色,選項 2 應更改為黃色。
我怎樣才能做到這一點?
這是在此下拉菜單上動態應用 css:
$(".custom-select").each(function() {
var classes = $(this).attr("class"),
id = $(this).attr("id"),
name = $(this).attr("name");
var template = '<div class="' + classes + '">';
template += '<span class="custom-select-trigger">' + $(this).attr("placeholder") + '</span>';
template += '<div class="custom-options">';
$(this).find("option").each(function() {
template += '<span class="custom-option ' + $(this).attr("class") + '" data-value="' + $(this).attr("value") + '">' + $(this).html() + '</span>';
});
template += '</div></div>';
$(this).wrap('<div class="custom-select-wrapper"></div>');
$(this).hide();
$(this).after(template);
});
$(".custom-option:first-of-type").hover(function() {
$(this).parents(".custom-options").addClass("option-hover");
}, function() {
$(this).parents(".custom-options").removeClass("option-hover");
});
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
$(".custom-option").on("click", function() {
$.LoadingOverlay("show");
$(this).parents(".custom-select-wrapper").find("select").val($(this).data("value"));
var id = $(this).parents(".custom-select-wrapper").find("select").attr("id");
var placeholder = $(this).parents(".custom-select-wrapper").find("select").attr("placeholder");
$(this).parents(".custom-options").find(".custom-option").removeClass("selection");
// alert(placeholder);
$(this).addClass("selection");
$(this).parents(".custom-select").removeClass("opened");
$(this).parents(".custom-select").find(".custom-select-trigger").text($(this).text());
我認為你可以做的是給每個選項一個新的類/id,或者將它們作為 CSS 中的子元素訪問,比如.custom-select-trigger > option
雖然,我更喜歡前者而不是后者,因為它允許更多和對選項的單獨控制。 你可以把它們寫成
<option value = "0" class = "option_0"> ---Content---</option>
然后您可以在 CSS 中使用 class 名稱訪問它。 要更改交互顏色,對於鼠標 hover,請使用
.option_0:hover{background: red;}
或點擊
.option_0:active{background: red;}
並為 rest 做同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.