Javascript:onClick复选框更改div颜色 [英] Javascript: onClick checkbox change div color
问题描述
< div id =question_text_1>
< input type =checkboxonChange =myFunction(question_text_1)>样本问题文本
< / div>
我试图切换 div $ c的背景颜色$ c>每当复选框被选中或未选中,这是行不通的。
这是完整的代码 然而,在没有切换逻辑的情况下实现相同的代码工作正常 - 链接
请建议可能会出现什么问题。
问题是, x.style.backgroundColor
仅当它被设置为内联样式时才值。它会返回rgb,而不是十六进制。您最好根据复选框的选中
属性进行验证:
< div id =question_text_1>
< input type =checkboxonChange =myFunction(question_text_1,this)>示例问题文本
< / div>
函数myFunction(x,_this){
x.style.backgroundColor = _this.checked? '#0000FF':'#FF0000';
}
http://codepen.io/anon/pen/avLrze
I've a check-box inside div.
<div id="question_text_1">
<input type="checkbox" onChange="myFunction(question_text_1)">Sample question text
</div>
I'm trying to toggle the background color of div
whenever checkbox is checked or unchecked, which is not working.
Here is the complete code
However, implementing same code without toggle logic is working fine - link
Kindly suggest what could be going wrong.
The problem is that x.style.backgroundColor
will return color's value only if it is set as inline style. And it will return rgb, not hex. You should better make the verification based on checked
attribute of the checkbox:
<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';
}
http://codepen.io/anon/pen/avLrze
这篇关于Javascript:onClick复选框更改div颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!