javascript - 通过查找输入背景颜色更改 div 颜色

标签 javascript html forms

如何更改 JavaScript 代码以找到 input label 的 HTML background-color 而不必手动插入颜色像这段代码一样进入 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>

关于javascript - 通过查找输入背景颜色更改 div 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041922/

相关文章:

html - 将django表单中的外键字段设置为只读,并且仍然允许提交表单

javascript - Json - 创建一个自动递增的 ID 列

php - 只有 txt 文件的最后一部分是 if 语句可读的

javascript - 覆盖 JQuery $ui.progressbar 以更改其宽度

javascript - CakePHP 无法读取 javascript 生成的克隆表单中的正确输入名称

javascript - 需要在两种表单的字段上使用javascript函数

javascript - puppeteer page.evaluate 路径与测试 ID

javascript - 单击 Rails 时显示原始照片

javascript - jQuery:动画设置为在页面加载时启动; IE 在开始之前等待动画的长度

javascript - DIV 坚持到顶部,直到被下一个 DIV 推到屏幕外