<div id="change" style="height:20px; width:100%; position: absolute; float:bottom; background-color:#000000">
</div> <br>
<select name="bgcolor" id="bgcolor" onchange="colorDiv()">
<option class="1" value=1> Grey
<option class="2" value=2> White
<option class="3" value=3> Blue
<option class="4" value=4> Cian
<option class="5" value=5> Green
</select> <br><br>
<p id="demo"></p>
<script>
function colorDiv(){
var selection = document.getElementById('bgcolor');
var div = document.getElementById( 'change' );
div.style.backgroundColor='green';
document.getElementById("demo").innerHTML =selection;
switch (selection){
case 1:
div.style.backgroundColor='grey';
case 2:
div.style.backgroundColor='white';
case 3:
div.style.backgroundColor='blue';
case 4:
div.style.backgroundColor='cian';
case 5:
div.style.backgroundColor='green';
}
</script>
Run Code Online (Sandbox Code Playgroud)
嗨!我正在尝试用js更改div的背景颜色,但它并没有检测到所选值,正如我在parragraph上打印时看到的那样.我已经在多个页面中看到了这个程序,它对我来说看起来是一样的,但它实际上对我的代码不起作用.你能看到任何错误吗?谢谢!!
option标签.document.getElementById('bgcolor').valuebreak每个case或div每次都会以绿色结束.case条件使用字符串.修改后的Javascript:
function colorDiv() {
var selection = document.getElementById('bgcolor').value;
var div = document.getElementById('change');
div.style.backgroundColor = 'green';
document.getElementById("demo").innerHTML = selection;
switch (selection) {
case "1":
div.style.backgroundColor = 'grey';
break;
case "2":
div.style.backgroundColor = 'white';
break;
case "3":
div.style.backgroundColor = 'blue';
break;
case "4":
div.style.backgroundColor = 'cian';
break;
case "5":
div.style.backgroundColor = 'green';
break;
}
}
Run Code Online (Sandbox Code Playgroud)
这个工作小提琴总结了它.
| 归档时间: |
|
| 查看次数: |
34894 次 |
| 最近记录: |