我有一个复选框内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