javascript - 如何从下拉菜单中更改 DIV 的背景颜色?

标签 javascript html css

是否可以根据最终用户从下拉列表中的选择更改 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/

相关文章:

javascript - 将 anchor 链接添加到 Div 及其伪元素(CSS 或 Javascript/jQuery)

javascript - 不带括号的多个 for 循环

javascript - 如何通过鼠标单击事件从动态表中选择一行

javascript - 向上滚动时如何重置 scrollTop() div 定位?

html - IE11 flexbox 容器不增长

javascript - 如何使用 html5-canvas 拖动连接线

css - 通过 bootstrap 制作自适应 div

css - 使用 ng-show 和 ng-animate 向上/向下滑动效果

javascript - 带有 js 的多个 ul tab 元素不起作用

javascript - 通过ajax传输数据到php