Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

javascript - Change Text Color of Selected Option in a Select Box

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 color of the closed select box to the color of the chosen option.

<select id="mySelect" class="yellowText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText" value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

So if I select Banana, the text should change from yellow to red.

I have tried:

onchange="this.style.color = this.options[this.selectedIndex].style.color;"

But this only works if I define my styles within the option tags inside html document.

I have also tried JavaScript:

function setSelectColor(thisElement){
    var thisElem = document.getElementById(thisElement);
    var thisOption = thisElem.options[thisElem.selectedIndex];
    var newColor = getStyle(thisOption,"color");
    alert("New Color: "+ newColor);
}

But this always returns the color: white. The getStyle function works everywhere else I use it so I do not believe that's the problem.

I got getStyle from this very website:

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/-(w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

How can I solve this with JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

.greenText{ background-color:green; }

.blueText{ background-color:blue; }

.redText{ background-color:red; }
<select
    onchange="this.className=this.options[this.selectedIndex].className"
    class="greenText">
     <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...