javascript-通过查找输入background-color更改div颜色
作者:互联网
如何更改JavaScript代码以找到输入标签的HTML背景颜色,而不必像在此代码段中那样手动将颜色插入JavaScript?
function ChangeColor(color) {
var clrDiv = document.getElementsByClassName("colorDiv")[0];
clrDiv.style.backgroundColor = color;
}
document.getElementById("select1").onclick = function() {
ChangeColor("red");
}
document.getElementById("select2").onclick = function() {
ChangeColor("green");
}
document.getElementById("select3").onclick = function() {
ChangeColor("blue");
}
.colorDiv {
width: 50px;
height: 50px;
}
<section>
<input id="select1" name="test" type="radio" />
<label style="background-color:red;" for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label style="background-color:green;" for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label style="background-color:blue;" for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>
解决方法:
这是你想要的?我传递颜色而不是颜色,传递选择的ID,找到输入的标签,然后使用该标签的背景色设置div背景色.
如果可以使用jquery,则可以大大简化.
function findLableForControl(el) {
var idVal = el.id;
labels = document.getElementsByTagName('label');
for( var i = 0; i < labels.length; i++ ) {
if (labels[i].htmlFor == idVal)
return labels[i];
}
}
function ChangeColor(color) {
var clrDiv = document.getElementsByClassName("colorDiv")[0];
clrDiv.style.backgroundColor = findLableForControl(document.getElementById(color)).style.backgroundColor;;
}
document.getElementById("select1").onclick = function() { ChangeColor("select1"); }
document.getElementById("select2").onclick = function() { ChangeColor("select2"); }
document.getElementById("select3").onclick = function() { ChangeColor("select3"); }
.colorDiv{
width:50px;
height:50px;
}
<section>
<input id="select1" name="test" type="radio" />
<label style="background-color:red;" for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label style="background-color:green;" for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label style="background-color:blue;" for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>
标签:html-form,html,javascript 来源: https://codeday.me/bug/20191109/2012618.html