pss*_*pss 1 html javascript checkbox onclick
我在div里面有一个复选框.
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1)">Sample question text
</div>
Run Code Online (Sandbox Code Playgroud)
我正在尝试切换div选中或取消选中复选框时的背景颜色,这不起作用.
这是完整的代码
但是,在没有切换逻辑的情况下实现相同的代码工作正常 - 链接
请建议可能出现的问题.
问题是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';
}
Run Code Online (Sandbox Code Playgroud)
http://codepen.io/anon/pen/avLrze