jquery在输入焦点上将类添加到父级

use*_*026 12 html css jquery

我有联系表格.我想在输入:focus上将类添加到输入框的父div.这是小提琴.我想要的不仅仅是输入框,而且div背景颜色应该在输入焦点上变为紫色.

标记:

<div class="round">
    <div class="round_label">name</div>
    <input type="text" class="round_text">
</div>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

jQuery(document).ready(function($) {
    $(".round_text:focus").parent().css('background', '#8b66ac');
    $('.round_text:focus').parent().css('background-color', 'red');
});
Run Code Online (Sandbox Code Playgroud)

CSS:

.round {
    background: none repeat scroll 0 0 #F3F3F3;
    border-radius: 30px 30px 30px 30px;
    border-top: 1px solid #B2B2B2;
    height: 50px;
    padding-left: 20px;
    width: 440px;
}
.round_text:focus {
    background: none repeat scroll 0 0 #8b66ac;
}
.round_label {
    border-right: 1px solid #D1D1D1;
    color: #B6B6B6;
    float: left;
    font-size: 16px;
    height: 40px;
    padding-top: 10px;
    width: 156px;
}
.round_text {
    background: none repeat scroll 0 0 #F3F3F3;
    border: medium none;
    color: #424242;
    float: left;
    height: 50px;
    width: 240px;
}
Run Code Online (Sandbox Code Playgroud)

另外,你能帮助我,好像我需要添加两个属性,例如:

$(".round_text").focus(function(){
       $(this).parent().css('background', '#8b66ac','color','#fff');

  }).blur(function(){
       $(this).parent().css('background', /*color*/);
  })
Run Code Online (Sandbox Code Playgroud)

She*_*wal 19

您可以改为添加类并给出样式

jQuery(document).ready(function($) {

 $(".text").focus(function(){
   $(this).parent().removeClass("round");
   $(this).parent().addClass("bluebg");

  }).blur(function(){
       $(this).parent().removeClass("bluebg");
   $(this).parent().addClass("round");
  })

});    

.bluebg {
background: none repeat scroll 0 0 #8b66ac;
color:#623886;
}
Run Code Online (Sandbox Code Playgroud)


cha*_*tfl 9

使用焦点事件

  $(".round_text").focus(function(){
       $(this).parent().css('background', '#8b66ac');

  }).blur(function(){
       $(this).parent().css('background', /*color*/);
  })
Run Code Online (Sandbox Code Playgroud)

编辑:使用toggleClass()的替代解决方案

CSS

.round_text:focus, .round.is_focused {
     background: none repeat scroll 0 0 #8b66ac;
}
Run Code Online (Sandbox Code Playgroud)

JS

$(".round_text").on('focus blur', function(){
     $(this).parent().toggleClass('is_focused');
})
Run Code Online (Sandbox Code Playgroud)