在 JQuery 中将选择的背景颜色设置为选定的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5068087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:30:17  来源:igfitidea点击:

Set background colour of select to selected option in JQuery

jquerycss

提问by meepmeep

Follow-up to this question: Setting background-color of select options in JQuery

这个问题的后续:Setting background-color of select options in JQuery

I have a page with multiple select boxes, as per the following:

我有一个带有多个选择框的页面,如下所示:

<select name="item-0-status" id="id_item-0-status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>

These are being auto-generated in django, so it is not possible to apply css classes, ids or attributes directly to the options. The select elements have ids of 'item-0-status','item-1-status','item-2-status' etc.

这些是在 django 中自动生成的,因此不可能将 css 类、id 或属性直接应用于选项。选择元素的 ID 为“item-0-status”、“item-1-status”、“item-2-status”等。

I am allocating colours to the options via the following JQuery code:

我通过以下 JQuery 代码为选项分配颜色:

$('select[id$=-status][id^=id_item-]').children().each(
        function (){
            if($(this).val() == 0){
                $(this).css('backgroundColor','white');
            }
            if($(this).val() == 1){
                $(this).css('backgroundColor','green');
            }
            if($(this).val() == 2){
                $(this).css('backgroundColor','red');
            }
            if($(this).val() == 3){
                $(this).css('backgroundColor','orange');
            }
        }
    );

Which works fine.

哪个工作正常。

I also want the select elements to have the same background colour as the selected option, which I am trying to achieve using the following:

我还希望选择元素与所选选项具有相同的背景颜色,我试图使用以下方法实现:

$('select[id$=-status][id^=id_item-]').each(
        function (){
            $(this).css('backgroundColor',$('option:selected',this).css('backgroundColor'));
        }
    );

However, this just colours the select element in blue (I think it is taking the colour from the hover property rather than the background). This is in Firefox 3.6.8, which for the purposes of this question is the only browser concerned.

但是,这只是将选择元素着色为蓝色(我认为它是从悬停属性而不是背景中获取颜色)。这是在 Firefox 3.6.8 中,就本问题而言,它是唯一相关的浏览器。

Any idea how to fix this?

知道如何解决这个问题吗?

回答by demux

Replace the "each" with "change"

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

$('select[id$=-status][id^=id_item-]').change(
    function (){
        var color = $('option:selected',this).css('background-color');
        $(this).css('background-color',color);
    }
).change();

This works in Chrome.

这适用于 Chrome。

Also see: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions

另请参阅:http: //docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions

Custom css in django admin is supported.

支持 django admin 中的自定义 css。

And I believe that the correct css attribute is: 'background-color'. backgroundColoris javascript and should be used like this: $(this).css({backgroundColor:color});But it seems to work anyway so no biggie.

我相信正确的 css 属性是:'background-color'. backgroundColor是 javascript,应该像这样使用: $(this).css({backgroundColor:color});但它似乎无论如何都可以工作,所以没什么大不了的。

EDIT:

编辑:

If you want to init the script on page load you can just add .change() behind. See code.

如果你想在页面加载时初始化脚本,你可以在后面添加 .change() 。见代码。

I also tested this in firefox and I also see this strange behavior (blue, wth blue?).

我也在 Firefox 中测试了这个,我也看到了这种奇怪的行为(蓝色,蓝色?)。

Another EDIT:

另一个编辑:

Ok, so here is a quick fix for 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();

Last EDIT:

最后编辑:

You could even to this if you're using css:

如果您使用 css,您甚至可以这样做:

<style>
    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;
    }
</style>

<script>    
    $('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();
</script>

Yet another edit:

另一个编辑:

I came across this and saw that I could make it shorter so I did just for fun:

我遇到了这个,发现我可以缩短它,所以我只是为了好玩:

$('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();

回答by Ahmed Mohamed

$("select[id$=-status][id^=id_item-]").change(function (){
    var style = $(this).find('option:selected').attr('style');
    $(this).attr('style', style);
    $("select[id$=-status][id^=id_item-] option:selected").each(function () {
            $(this).attr('style', style);
          });
}).trigger('change');

Add style to you HTML code, use trigger don't forget to load this in your $(document).ready(function(){}Also don't forget to put this code after populating your Select box from the DB

为您的 HTML 代码添加样式,使用触发器 不要忘记将其加载到您的$(document).ready(function(){}也不要忘记在从数据库填充您的选择框后放置此代码

回答by Dan

I like @Arnar Yngvason's answer but I'll add this to the mix. This solution uses CSS classes so the styles can be easily changed without breaking the rest of the code.

我喜欢@Arnar Yngvason 的回答,但我会将其添加到组合中。此解决方案使用 CSS 类,因此可以轻松更改样式而不会破坏其余代码。

Html

html

<select>
    <option class="Red">Red</option>
    <option class="Blue">Blue</option>
    <option class="Green">Green</option>
    <option class="Yellow">Yellow</option>
</select>
<div id="output"></div>

CSS

CSS

.Red{background-color:#ff0000;}
.Blue{background-color:#0000ff;}
.Green{background-color:#00ff00;}
.Yellow{background-color:#ffff00;}

JavaScript

JavaScript

$("select").change(function(){
    $(this).removeClass($(this).attr('class'))
           .addClass($(":selected",this).attr('class')); 
    /*If you want to keep some classes just add them back here*/
    //Optional: $(this).addClass("Classes that should always be on the select");

});

 $("select").change(function() {
   $(this).removeClass($(this).attr('class'))
     .addClass($(":selected", this).attr('class'));
   /*If you want to keep some classes just add them back here*/
   //Optional: $(this).addClass("Classes that should always be on the select");

 });
    .Red {
      background-color: #ff0000;
    }
    .Blue {
      background-color: #0000ff;
    }
    .Green {
      background-color: #00ff00;
    }
    .Yellow {
      background-color: #ffff00;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option class="Red">Red</option>
  <option class="Blue">Blue</option>
  <option class="Green">Green</option>
  <option class="Yellow">Yellow</option>
</select>
<div id="output"></div>

JSFiddle

JSFiddle

I've tested this on FireFox 31, IE 11 and Chrome 37

我已经在 FireFox 31、IE 11 和 Chrome 37 上测试过了