set Different colors in asp:DropDownList Items

前端 未结 3 1510
滥情空心
滥情空心 2021-01-22 10:49

I have an in my form, with 4 different options (items) What I need to do it\'s to set a different color from client side, without PostBack.

Items:

  • Selec
3条回答
  •  广开言路
    2021-01-22 11:07

    This markup applies a different background color to each item, and sets the onchange event handler:

    
        Select...
        Complete
        Running
        Waiting in SEV 1
        No Batch
    
    

    The following Javascript ensures that the color of the selection box matches the color of the selected item:

    function SetDropDownListColor(ddl) {
        for (var i = 0; i < ddl.options.length; i++) {
            if (ddl.options[i].selected) {
                switch (i) {
                    case 0:
                        ddl.style.backgroundColor = 'White';
                        return;
    
                    case 1:
                        ddl.style.backgroundColor = 'Green';
                        return;
    
                    case 2:
                        ddl.style.backgroundColor = 'Yellow';
                        return;
    
                    case 3:
                        ddl.style.backgroundColor = 'Red';
                        return;
    
                    case 4:
                        ddl.style.backgroundColor = 'Blue';
                        return;
                }
            }
        }
    }
    

    The !important modifier is set in the markup of the items in the list, in order to override the background color set to the whole control in the Javascript function.

    In order to preserve the color of the DropDownList after a postback, the following line of code can be added to the Javascript block. It defines a handler for the load event of the page, in which the color of the selected item is applied to the selection box:

    window.addEventListener('load', function () { SetDropDownListColor(document.getElementById('<%= DropDownList1.ClientID %>')); }, false);
    

提交回复
热议问题