Javascript:onClick复选框更改div颜色 [英] Javascript: onClick checkbox change div color

查看:90
本文介绍了Javascript:onClick复选框更改div颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div里面有一个复选框。

 < div id =question_text_1> 
< input type =checkboxonChange =myFunction(question_text_1)>样本问题文本
< / div>

我试图切换 div 每当复选框被选中或未选中,这是行不通的。



这是完整的代码 然而,在没有切换逻辑的情况下实现相同的代码工作正常 - 链接



请建议可能会出现什么问题。

解决方案

问题是, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆