更改元素的背景颜色?

时间:2013-10-08 10:18:53

标签: javascript dom

我有javascript的问题,对不起,但我不擅长Javascript

我正在尝试,在其他元素上运行cnagecolor,并将颜色传递给我想要的,但没有运气:(

这就是我现在所拥有的

<script>
function changeColor(i) {
    var col = document.getElementById("changecolor");
    col.style.backgroundColor = '+i+';
}
</script>
<select id="changecolor">
<option>Kategorija</option>
<option onclick="changeColor('rgb(51,51,51)');" style="background-color:rgb(51,51,51);"></option>
<option onclick="changeColor('rgb(0,51,255)');" style="background-color:rgb(0,51,255);"></option>
<option onclick="changeColor('rgb(204,0,153)');" style="background-color:rgb(204,0,153)"></option>
<option onclick="changeColor('rgb(255,204,153)');" style="background-color:rgb(255,204,153)"></option>
</select>

4 个答案:

答案 0 :(得分:3)

尝试类似......

<script>
    function changeColor() {
        var col = document.getElementById("changecolor");
        col.style.backgroundColor = col.value;
    }
</script>

 <select onchange="changeColor()" id="changecolor">
<option >Kategorija</option>
<option value="rgb(51,51,51)" style="background-color:rgb(51,51,51);"></option>
<option value="rgb(0,51,255)" style="background-color:rgb(0,51,255);"></option>
<option value="rgb(204,0,153)" style="background-color:rgb(204,0,153)"></option>
<option value="rgb(255,204,153)" style="background-color:rgb(255,204,153)"></option>
</select>

答案 1 :(得分:0)

试试这个

col.style.backgroundColor = i;

答案 2 :(得分:0)

选项标记不支持

'onclick'事件(以及'onselect')。因此,您可以使用'onchange'代替:

function select_onChange() {
   var selectElem = document.getElementById("changecolor");
   selectElem.style.backgroundColor = selectElem.value;
}

<select id="changecolor" onchange="select_onChange()">
   <option value="rgb(51,51,51)" style="background-color:rgb(51,51,51);">Option #1</option>
   <option value="rgb(0,51,255)" style="background-color:rgb(0,51,255);">Option #2</option>
</select>

答案 3 :(得分:0)

你可以这样做......

<script>
    // Execute this function on change of the select
    function changeColor() {
    var col = document.getElementById("changecolor");
    // Get the value of selected option in select
    var values = col.options[col.selectedIndex].value;
    col.style.backgroundColor = values;
}

</script>

<select id="changecolor" onchange="changeColor();">
<option>Kategorija</option>
<option value="rgb(51,51,51)">a</option>
<option value="rgb(0,51,255)">v</option>
<option value="rgb(204,0,153)">s</option>
<option value="rgb(255,204,153)">d</option>
</select>