select选中css背景色,将select的背景色设置为JQuery中的选定选项

小编典典

将“每个”替换为“更改”

$('select[id$=-status][id^=id_item-]').change(

function (){

var color = $('option:selected',this).css('background-color');

$(this).css('background-color',color);

}

).change();

这适用于Chrome。

另请参阅:http :

//docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-

definitions

支持django admin中的自定义CSS。

而且我认为正确的CSS属性是:'background-color'。 backgroundColor是javascript,应按以下方式使用:

$(this).css({backgroundColor:color});但是它似乎仍然可以正常工作,所以没什么大不了的。

编辑:

如果要在页面加载时初始化脚本,则只需在后面添加.change()即可。参见代码。

我也在firefox中进行了测试,并且也看到了这种奇怪的行为(蓝色,蓝色?)。

另一个编辑:

好的,所以这是Firefox的快速修复:

$('select[id$=-status][id^=id_item-]').children().each(function (){

if($(this).val() == 0){

$(this).attr('style', 'background-color:white;');

}

if($(this).val() == 1){

$(this).attr('style', 'background-color:green;');

}

if($(this).val() == 2){

$(this).attr('style', 'background-color:red;');

}

if($(this).val() == 3){

$(this).attr('style', 'background-color:orange;');

}

});

$('select[id$=-status][id^=id_item-]').change(function (){

var style = $(this).find('option:selected').attr('style');

$(this).attr('style', style);

}).change();

最后编辑:

如果使用CSS,甚至可以做到这一点:

select option,

select {

background-color:white;

}

select option[value="1"],

select.o1

{

background-color:green;

}

select option[value="2"],

select.o2

{

background-color:red;

}

select option[value="3"],

select.o3

{

background-color:orange;

}

$('select[id$=-status][id^=id_item-]').change(function (){

var color = $(this).find('option:selected').val();

$(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());

}).change();

另一个编辑:

我碰到了这一点,发现可以将其缩短,所以我只是为了好玩而已:

$('select[id$=-status][id^=id_item-]').children().each(function() {

var colors = ['white', 'green', 'red', 'orange'];

$(this).attr('style', 'background-color:' + colors[$(this).val()] + ';');

});

$('select[id$=-status][id^=id_item-]').change(function() {

$(this).attr('style', $(this).find('option:selected').attr('style'));

}).change();

2020-05-16

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值