[英]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.