【问题标题】:jquery add class to parent on input focusjquery在输入焦点上向父级添加类
【发布时间】:2012-06-08 08:06:24
【问题描述】:

我有一个联系表。我想在 input:focus 上向输入框的父 div 添加类。 这是fiddle。我希望不仅输入框,而且 div 背景颜色在输入焦点上应更改为紫色。

标记:

<div class="round">
    <div class="round_label">name</div>
    <input type="text" class="round_text">
</div>

Javascript:

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

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;
}

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

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

  }).blur(function(){
       $(this).parent().css('background', /*color*/);
  })

【问题讨论】:

  • 始终添加有问题的代码以及 jsfiddle 链接
  • 感谢您的建议。从下次开始会这样做。

标签: jquery html css


【解决方案1】:

您可以改为添加类并赋予样式

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;
}

【讨论】:

  • 有没有办法在没有 jQuery 的情况下做到这一点?
【解决方案2】:

使用焦点事件

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

  }).blur(function(){
       $(this).parent().css('background', /*color*/);
  })

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

CSS

.round_text:focus, .round.is_focused {
     background: none repeat scroll 0 0 #8b66ac;
}

JS

$(".round_text").on('focus blur', function(){
     $(this).parent().toggleClass('is_focused');
})

【讨论】:

  • 完美答案:) 谢谢
【解决方案3】:

试试这个

 $("input").on("focus",function(){
    $(this).parent().addClass("any_class").css("background","purple");
    });

【讨论】:

  • 为什么要添加类并使用 css() 方法?
  • 我已阅读标题,其中 op 想要向父级添加类,并且在描述中他想将背景设置为紫色,因此我同时设置了
【解决方案4】:

如果我没看错你的问题,

您正在选择 focused 元素,但您需要在 focus 事件上更改父 div 的 css。

这样做,

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

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

Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多