我想使用一个下拉菜单,该菜单将使用 JavaScript 更改文档的 bgColor
I want to use a dropdown menu that will change the bgColor of the document using JavaScript
我正在寻找使用开关和数组来更改使用 javascript 和 html 的文档的 bgColor。
这是我的代码:
function changebg() {
var colors = ["red", "blue", "pink", "orange", "yellow", "green"];
x = document.bgColor
y = document.getElementById("selection").value;
switch (y) {
case "red":
x = colors[0];
break;
case "blue":
x = colors[1];
break;
case "pink":
x = colors[2];
break;
case "orange":
x = colors[3];
break;
case "yellow":
x = colors[4];
break;
case "green":
x = colors[5];
break;
}
}
document.bgColor = changebg();
不确定从这里去哪里,有什么建议吗?
return x
在 changebg()
.
结尾
我有一个 JSFiddle 给你。这是您要找的吗?
您只需将此 document.body.style.backgroundColor = x;
添加到您的函数中即可。
您可以删除开关并仅使用 select 元素中的值。这将是更清洁的方式。
对于 starter 你可以试试这个:
document.getElementById("selection").addEventListener("change",function(){
document.body.style.backgroundColor=this.value;
},false);
<select size="1" id="selection">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<select>
积分:
- 在
<option>
中使用 value
属性;
- 使用
document.body.style
.backgroundColor
(or document.body.className
/document.body.classList
) 而不是 document.bgColor
.
我正在寻找使用开关和数组来更改使用 javascript 和 html 的文档的 bgColor。
这是我的代码:
function changebg() {
var colors = ["red", "blue", "pink", "orange", "yellow", "green"];
x = document.bgColor
y = document.getElementById("selection").value;
switch (y) {
case "red":
x = colors[0];
break;
case "blue":
x = colors[1];
break;
case "pink":
x = colors[2];
break;
case "orange":
x = colors[3];
break;
case "yellow":
x = colors[4];
break;
case "green":
x = colors[5];
break;
}
}
document.bgColor = changebg();
不确定从这里去哪里,有什么建议吗?
return x
在 changebg()
.
我有一个 JSFiddle 给你。这是您要找的吗?
您只需将此 document.body.style.backgroundColor = x;
添加到您的函数中即可。
您可以删除开关并仅使用 select 元素中的值。这将是更清洁的方式。
对于 starter 你可以试试这个:
document.getElementById("selection").addEventListener("change",function(){
document.body.style.backgroundColor=this.value;
},false);
<select size="1" id="selection">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<select>
积分:
- 在
<option>
中使用value
属性; - 使用
document.body.style
.backgroundColor
(ordocument.body.className
/document.body.classList
) 而不是document.bgColor
.