问题
Is it possible to change the background color of a DIV based on the end-user's selection from a drop down list? For example, I have a drop down menu with options for blue, green, red, etc. and I would like the DIV background color to be whatever the user selects. Here is what i tried but I cannot figure out how to get it it work:
<head>
<style>
div.results{
position: relative;
left: 300px;
height: 200px;
width: 200px;
border: 1px solid;
color: black;
}
</style>
<script>// this script will place the background image.
function selectBackground(){
var e = document.getElementById("selector");
var BackgroundValue = e.options[e.selectedIndex].value;
document.getElementById("PreviewResults").style.background-color= BackgroundValue;
}
</script>
</head>
<body>
<div class="selectors">
<select id=selector>
<option>Select Background</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<button onclick="selectBackground()">Preview Results</button>
</div>
<div class="results" id="PreviewResults" style="background-color:white;">
Results Here
</div>
</body>
回答1:
document.getElementById("PreviewResults").style.background-color= BackgroundValue;
This doesn’t work, because what you have here would a subtraction operation in JavaScript, because - is the operator for that.
To access any style properties that contain - you need to either remove the - and replace the following letter with its uppercase version:
document.getElementById("PreviewResults").style.backgroundColor = BackgroundValue;
or use the square bracket syntax:
document.getElementById("PreviewResults").style["background-color"] = BackgroundValue;
回答2:
Make sure you are using style.backgroundColor to actually set your background :
document.getElementById("PreviewResults").style.background-color= BackgroundValue;
You also may want to consider setting the value of your default option to transparent (the initial value for the background) so that the user could switch back after a change was made :
<select id=selector>
<option value="transparent">Select Background</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
You can see an example of this in action here and demonstrated below :
回答3:
Change the line
document.getElementById("PreviewResults").style.background-color= BackgroundValue;
to
document.getElementById("PreviewResults").style.backgroundColor = BackgroundValue;
来源:https://stackoverflow.com/questions/36525391/how-to-change-the-background-color-of-a-div-from-a-dropdown-menu