[英]How to change the document background color when select list option for that color is selected
function change_color() { var getSelect = document.getElementsByName("colorPick"); var selection = getSelect.options[getSelect.selectedIndex].value; for (i = 0; i < getSelect.options.length; i++) { document.body.style.backgroundColor = selection; } }
<select name="colorPick" onchange="change_color();"> <option value="0">Background Color</option> <option value="1">Blue</option> <option value="2">Cyan</option> <option value="3">White</option> </select>
/ 出问题了。 我尝试了许多不同的操作,但是选择颜色似乎无济于事。 /
您的代码无法正常工作,因为getElementsByName
返回了元素的nodeList集合。 您无法访问集合的值,因此需要访问其中一个元素。
document.getElementsByName("colorPick")[0]; // First element
您可以通过传递select元素的上下文来避免这种情况: onchange="change_color(this)"
。
在更改背景颜色方面,您需要将body
元素的背景颜色设置为所选元素的文本 。 没有价值。
function change_color(select) { var color = select.options[select.selectedIndex].textContent; document.body.style.backgroundColor = color; }
<select name="colorPick" onchange="change_color(this);"> <option value="0">Background Color</option> <option value="1">Blue</option> <option value="2">Cyan</option> <option value="3">White</option> </select>
我建议尽管使用不引人注目的JavaScript :
document.querySelector('[name="colorPick"]').addEventListener('change', function () { var color = this.options[this.selectedIndex].textContent; document.body.style.backgroundColor = color; });
<select name="colorPick"> <option value="0">Background Color</option> <option value="1">Blue</option> <option value="2">Cyan</option> <option value="3">White</option> </select>
它是这样的:
<body>
<select name="colorPick" onchange="change_color();">
<option value="0">Background Color</option>
<option value="Blue">Blue</option>
<option value="Cyan">Cyan</option>
<option value="White">White</option>
</select>
</body>
JavaScript的:
function change_color() {
var getSelect = document.getElementsByName("colorPick");
var selection = getSelect[0].options[getSelect[0].selectedIndex].value;
for (i = 0; i < getSelect[0].options.length; i++) {
document.body.style.backgroundColor = selection;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.