是否可以根据最终用户从下拉列表中的选择更改 DIV 的背景颜色?例如,我有一个带有蓝色、绿色、红色等选项的下拉菜单,我希望 DIV 背景颜色是用户选择的任何颜色。这是我尝试过的方法,但我不知道如何让它工作:
<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>
最佳答案
document.getElementById("PreviewResults").style.background-color= BackgroundValue;
这是行不通的,因为你这里有一个 JavaScript 中的减法运算,因为 -
是它的运算符。
要访问任何包含 -
的样式属性,您需要删除 -
并将以下字母替换为其大写版本:
document.getElementById("PreviewResults").style.backgroundColor = BackgroundValue;
或使用方括号语法:
document.getElementById("PreviewResults").style["background-color"] = BackgroundValue;
关于javascript - 如何从下拉菜单中更改 DIV 的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36525391/