简体   繁体   English

单击输入字段时更改div背景颜色

[英]changing div background color when clicking on input field

I would like to change the color of the div that my input field is in when a user clicks on the input field to enter content and/or when they click in the div area. 当用户单击输入字段以输入内容和/或单击div区域时,我想更改输入字段所在的div的颜色。 If the user decides to not enter any content or erase the content they entered in the input field it would go back to the default color. 如果用户决定不输入任何内容或删除他们在输入字段中输入的内容,它将恢复为默认颜色。

The link below showcases what I would like to achieve. 下面的链接展示了我想要实现的目标。 I currently have an active state set on the div to showcase what color I would like the div to change to. 我目前在div上设置了一个活动状态,以展示我希望div更改为哪种颜色。 I realize that I will need to incorporate javascript to possibly achieve want I want to happen. 我意识到,我将需要合并javascript以实现我想要发生的希望。 Is anyone willing to give some assistance? 有人愿意提供帮助吗? Thanks. 谢谢。

Code: https://jsfiddle.net/L1ptj0ey/3/ 代码: https //jsfiddle.net/L1ptj0ey/3/

HTML HTML

 .other-area { width: 100%; height: 3.5rem; margin-top: 1.2rem; margin-bottom: 1.6rem; background-color: #cccbc9; border-radius: 4px; font-family: "Source Sans Pro", sans-serif; font-size: 1.4rem; font-weight: 600; padding-left: .9rem; } .other-area:active { background-color: #cd1e41; color: #FFF; } .other-input { border-top-right-radius: .4rem; border-bottom-right-radius: .4rem; height: 3.3rem; width: 19.3rem; margin-top: .1rem; margin-left: .9rem; padding-left: .5rem; color: #cccbc9; font-size: 1.4rem; font-weight: 600; font-family: "Source Sans Pro", sans-serif; } 
 <div class="other-area"> <span>Other Amount</span> <input type="number" name="otherAmount" value="$" class="other-input" /> </div> 

You can use focus and blur events of .other-input to change the styles of .other-area . 您可以使用.other-input focusblur事件来更改.other-area的样式。

 window.onload = function() { var div = document.getElementsByClassName('other-area')[0]; var input = document.getElementsByClassName('other-input')[0]; input.addEventListener('focus', function() { div.style.background = '#cd1e41'; div.style.color = '#FFF'; }); input.addEventListener('blur', function() { div.style.background = '#cccbc9'; div.style.color = '#000'; }); } 
 .other-area { width: 100%; height: 3.5rem; margin-top: 1.2rem; margin-bottom: 1.6rem; background-color: #cccbc9; border-radius: 4px; font-family: "Source Sans Pro", sans-serif; font-size: 1.4rem; font-weight: 600; padding-left: .9rem; } .other-input { border-top-right-radius: .4rem; border-bottom-right-radius: .4rem; height: 3.3rem; width: 19.3rem; margin-top: .1rem; margin-left: .9rem; padding-left: .5rem; color: #cccbc9; font-size: 1.4rem; font-weight: 600; font-family: "Source Sans Pro", sans-serif; } 
 <div class="other-area"> <span>Other Amount</span> <input type="number" name="otherAmount" value="$" class="other-input" /> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM