2016-08-15 137 views
0

此处有一个按钮,并添加了两个复选框。我试图做的是,当我点击任何复选框时,按钮颜色应该更改为绿色或任何其他颜色。如果我取消选中所有框,按钮颜色应该变成灰色。请帮帮我。谢谢。如何更改按钮的颜色单击复选框

.input { 
 
    font-weight: bold; 
 
    border-radius: 1px; 
 
    background-color: grey; 
 
}
<input id="input" class="" value=" ... " type="button"> 
 

 
<input type="checkbox" class="check-box"> 
 
<input type="checkbox" class="check-box"> 
 
<input type="checkbox" class="check-box">

回答

4

var elems = document.querySelectorAll('.check-box'); 
 
var btn = document.querySelector('.btn-elem'); 
 
[].forEach.call(elems, function(el) { 
 
    el.addEventListener('change', function() { 
 
    var checked = document.querySelectorAll('.check-box:checked'); 
 
    if (checked.length) { 
 
     btn.style.backgroundColor = 'green'; 
 
    } else { 
 
     btn.style.backgroundColor = ''; 
 
    } 
 
    }); 
 
});
<input class="btn-elem" value=" ... " style="font-weight: bold; border-radius: 1px; background-color: grey;" type="button"> 
 

 
<input type="checkbox" class="check-box"> 
 
<input type="checkbox" class="check-box"> 
 
<input type="checkbox" class="check-box">

+0

这是非常好的。它的工作完美。感谢您的努力。 –

2

这里是唯一使用纯JavaScript的例子(没有的jQuery):

var button = document.getElementById("mybtn"); 
 
var chkbox = document.getElementsByClassName("chkbox"); 
 

 
function onChangeListener() { 
 
    button.style.backgroundColor = "gray"; 
 
    for (var i = 0; i < chkbox.length; i++) { 
 
     if (chkbox[i].checked) { 
 
      button.style.backgroundColor = "green"; 
 
     } 
 
    } 
 
} 
 

 
for (var i = 0; i < chkbox.length; i++) { 
 
    var checkbox = chkbox[i]; 
 
    checkbox.addEventListener("change", onChangeListener); 
 
}
<input type="button" id="mybtn" value=" . . . " style="background-color: gray;"> 
 

 
<input type="checkbox" class="chkbox"> 
 
<input type="checkbox" class="chkbox"> 
 
<input type="checkbox" class="chkbox">

小提琴这里:https://jsfiddle.net/avh4dsnm/1/

+0

这也帮助我。非常感谢 –

1

要在丽阳的优秀稍微详细回答,并使其更具活力。你可以使用一个数据属性来指定按钮的颜色是例如

<input type="checkbox" class="check-box" data-color="green"> 
<input type="checkbox" class="check-box" data-color="blue"> 

你会再需要另一个变量的颜色

var colour = checked.dataset.color; 
if (checked.length) { 
    btn.style.backgroundColor = colour; 
} else { 
    btn.style.backgroundColor = ''; 
} 
1

只是为了好玩,这里有一个唯一的CSS-解决方案:

#input { 
 
    font-weight: bold; 
 
    border-radius: 1px; 
 
    background-color: grey; 
 
    float:left; 
 
} 
 
input:checked ~ #input { 
 
    background:green; 
 
}
<input type="checkbox" class="check-box"> 
 
<input type="checkbox" class="check-box"> 
 
<input type="checkbox" class="check-box"> 
 

 
<input id="input" class="" value=" ... " type="button">