选中时更改选项的颜色 [英] Change the color of an option when selected
问题描述
我希望有一个选项可以在用户选择时更改颜色.例如:用户选择红色选项,则将运行一个将颜色更改为红色的函数.如果用户随后选择绿色,则它将变为绿色.等等
I want an option to change color when selected by a user. For Example: a user selects the red option then a function would run that would change the color red. If the user then selected green then it would change green. etc.
<select onchange="changeColor();" class="color" id="rgb">
<option id="red" value="Red">Red</option>
<option id="green" value="Green">Green</option>
<option id="blue" value="Blue">Blue</option>
</select>
我从下面的函数开始,但是我不确定哪里出错了.
I started with the function below but I'm not sure where I went wrong.
function changeColor() {
var red = document.getElementById('red');
var green = document.getElementById('green');
var blue = document.getElementById('blue');
if(event.target.value == red) {
red.style.color = "red";
} else if(event.target.value == green) {
green.style.color = "green";
} else if(event.target.value == blue) {
blue.style.color = "blue";
} else {
alert("There was an error!");
}
};
推荐答案
尝试一下.当您选择一个选项时,您将在colorParam
中收到<select>
元素.如果选择第一个选项,则会在colorParam.value
中获得Red
,但是在lowerCase中使用的是ID,因此可以使用toLowerCase()
函数对其进行转换.然后选择option
元素并应用样式.
Try this. When you select an option you will recieve the <select>
element in colorParam
. If you select the first option, you will get Red
in colorParam.value
, but you are using IDs in lowerCase, so you can use toLowerCase()
function to convert it. Then select the option
element and apply styles.
function changeColor(colorParam) {
let color = colorParam.value.toLowerCase();
var optionElement = document.getElementById(color);
optionElement.style.color = color;
};
<select onchange="changeColor(this);" class="color" id="rgb">
<option id="red" value="Red">Red</option>
<option id="green" value="Green">Green</option>
<option id="blue" value="Blue">Blue</option>
<option id="white" value="White">White</option>
<option id="pink" value="Pink">Pink</option>
</select>
这篇关于选中时更改选项的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!