[英]Javascript: onClick checkbox change div color
問題是x.style.backgroundColor
僅在將其設置為嵌入式樣式時才返回顏色的值。 它將返回rgb,而不是十六進制。 您最好根據復選框的checked
屬性進行驗證:
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1, this)">Sample question text
</div>
function myFunction(x, _this) {
x.style.backgroundColor = _this.checked ? '#0000FF' : '#FF0000';
}
該代碼無效,因為x.style.backgroundColor
始終返回''
-空字符串, else
執行塊。
要獲取值,請參閱如何在javascript中獲取HTML元素的樣式值?
您可以使用CSS來實現,而無需使用Javascript
label
元素中的復選框關聯的文本換行 :checked
屬性可以在選中復選框時應用樣式 +
)在標簽上設置樣式 :checked + label { color: green; font-weight: bold; }
<div id="question_text_1"> <input type="checkbox" id="check1"> <label for="check1">Sample question text</label> </div>
如果要使用Javascript,請使用classList
!important
覆蓋類中的樣式,因為id選擇器具有更高的特異性 classList.toggle
切換類 function myFunction(x) { x.classList.toggle('blue'); }
#question_text_1 { background-color: #FF0000; padding: 7px; margin: 7px; } .blue { background-color: #00f !important; }
<div id="question_text_1"> <input type="checkbox" onChange="myFunction(question_text_1)">Sample question text </div>
請按如下所示更改您的代碼,效果很好
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1,this)">Sample question text
</div>
function myFunction(x,y) {
if (y.checked)
x.style.backgroundColor = '#0000FF';
else
x.style.backgroundColor = '#FF0000';
}
您不能直接將div背景色與color值進行比較,因為為此必須必須聲明與不同瀏覽器相關的color變量,請訪問此鏈接。 如何在Javascript中比較backgroundColor?
如果條件不使用x.style.backgroundColor ,請使用window.getComputedStyle(x).backgroundColor並與等效的'rgb'顏色進行比較。
function myFunction(x) {
if (window.getComputedStyle(x).backgroundColor == "rgb(255, 0, 0)") {
x.style.backgroundColor = '#0000FF';
} else if (window.getComputedStyle(x).backgroundColor == "rgb(0, 0, 255)"){
x.style.backgroundColor = '#FF0000';
}
}
希望這可以幫助。
謝謝
您可以像這樣使用jQuery進行嘗試:
的HTML
<input type="checkbox" id="my_checkbox"/>
<div id="toggle_color">Color Will change here</div>
jQuery的
jQuery(document).ready(function($){
$('#my_checkbox').on('change', function(){
if($(this).is(':checked')){
$("#toggle_color").css('background-color',"red");
} else {
$("#toggle_color").css('background-color',"#fff");
}
})
})
檢出jsfiddle 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.