2016-08-15 135 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">