问题
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'm started with the function below but im 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!");
}
};
回答1:
It looks like you haven't added an 'event' parameter to your function. Try this:
function changeColor(event) {
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!");
}};
回答2:
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>
回答3:
I'm not sure you can style an <option> element. You can style the <select> element though. However, color doesn't seem to be a property you can change, background-color is.
If that's all you need you could as well inline the javascript code in the onchange handler attribute. You would need to set the values of the <option> elements to valid css colours.
<select onchange="this.style.backgroundColor=this.value">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
来源:https://stackoverflow.com/questions/53356775/change-the-color-of-an-option-when-selected-javascript