我有一个选择框.这些选项通过已引用的CSS文件设置了不同颜色的样式.我希望能够选择一个选项并将关闭的选择框的文本颜色更改为所选选项的颜色.
<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>
Run Code Online (Sandbox Code Playgroud)
因此,如果我选择Banana,文本应该从黄色变为红色.
我试过了:
onchange="this.style.color = this.options[this.selectedIndex].style.color;"
Run Code Online (Sandbox Code Playgroud)
但这只有在我在html文档中的选项标签中定义我的样式时才有效.
我也试过JavaScript:
function setSelectColor(thisElement){
var thisElem = document.getElementById(thisElement);
var thisOption = thisElem.options[thisElem.selectedIndex];
var newColor = getStyle(thisOption,"color");
alert("New Color: "+ newColor);
}
Run Code Online (Sandbox Code Playgroud)
但这总是会返回颜色:白色.getStyle函数适用于我使用它的其他任何地方,所以我不相信这是问题所在.
我从这个网站得到了getStyle:
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;
}
Run Code Online (Sandbox Code Playgroud)
我如何用JavaScript解决这个问题?