我有一個複選框內div。Javascript:onClick複選框更改div顏色
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1)">Sample question text
</div>
我想只要複選框被選中或取消選中,這是不工作的切換的div
背景顏色。
然而,實現無切換邏輯相同的代碼工作正常 - link
請有什麼建議可以去錯了。
我有一個複選框內div。Javascript:onClick複選框更改div顏色
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1)">Sample question text
</div>
我想只要複選框被選中或取消選中,這是不工作的切換的div
背景顏色。
然而,實現無切換邏輯相同的代碼工作正常 - link
請有什麼建議可以去錯了。
問題是僅當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
塊被執行。
爲了獲取值看How to get an HTML element's style values in javascript?
你可以做到這一點使用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>
你可以試試像這樣的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。
而不是x.style.backgroundColor在if條件使用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';
}
}
希望這會有所幫助。
感謝
請更改像下面你的代碼,它工作正常
<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的背景顏色與顏色的值,因爲它必須要聲明的顏色相關的變量到不同的瀏覽器 爲此訪問此鏈接 How to compare a backgroundColor in Javascript?
沒有'jQuery'標籤 – Tushar