Change Text Color of Selected Option in a Select Box

前端 未结 6 1771
南笙
南笙 2020-12-02 22:54

I have a select box. The options have been styled with different colors via a CSS file that has been referenced. I want to be able to select an option and change the text co

6条回答
  •  孤街浪徒
    2020-12-02 23:35

    You could do it like this.

    jsFiddle

    JS

    var select = document.getElementById('mySelect');
    select.onchange = function () {
        select.className = this.options[this.selectedIndex].className;
    }
    

    CSS

    .redText {
        background-color:#F00;
    }
    .greenText {
        background-color:#0F0;
    }
    .blueText {
        background-color:#00F;
    }
    

    You could use option { background-color: #FFF; } if you want the list to be white.

    HTML

    
    

    Since this is a select it doesn't really make sense to use .yellowText as none selected if that's what you were getting at as something must be selected.

提交回复
热议问题