【问题标题】:jQuery taking control over label's border colorjQuery 控制标签的边框颜色
【发布时间】:2011-12-23 06:04:24
【问题描述】:

我的 jQuery 函数是这样的

$('input[type="text"]').focus(function() {  
       $("label").css("border-bottom-color", "red");
    });  
    $('input[type="text"]').blur(function() {  
       $("label").css("border-bottom-color", "#e6e6e6");
    });  

1) 我的表单中有一堆文本输入。我想要做的是更改焦点文本框标签的底部边框颜色(每个文本框都有一个标签。我只想更改焦点文本框标签的边框颜色)。但是我的函数一次改变了所有标签的边框颜色。如何解决这个问题?

2) 我有 2 个表格。带有 id 的 form1 和 form2。我想对第二种形式做同样的事情,但颜色会是另一种。如何修改这个函数?

我的表格是这样的

<form id="form1">
 ...
<label for="fname">First Name</label>
<input name="fname" placeholder="please enter your first name" type="text" /> 
 ...
</form>

<form id="form2">
 ...
<label for="job">Your Job</label>
 ...
<input name="job" placeholder="please enter your job" type="text" />
</form>

【问题讨论】:

    标签: javascript jquery css colors border


    【解决方案1】:

    这个小提琴怎么样?

    http://jsfiddle.net/RvYca/3/

    label 标签的for 属性引用inputid 属性,而不是它的name。 我也将样式移到了 css 中。

    【讨论】:

    • 如何修改输入类型文本和密码的函数?
    • 很简单:$('input[type="text"],input[type="password"]') 或者只使用 $('input')... 如果可以的话。
    • 我有 2 个表格。带有 id 的 form1 和 form2。我想对第二种形式做同样的事情,但颜色会是另一种。如何修改这个函数?
    • 你只需要修改css,见更新的小提琴:jsfiddle.net/RvYca/3
    【解决方案2】:

    同时使用 CSS 和 JavaScript:

    $('input:text, input:password, textarea').focus(
        function(){
            $(this).prev('label').addClass('focused');
        }).blur(
        function(){
            $(this).prev('label').removeClass('focused');
        });
    

    而且,在 CSS 中:

    #form1 label.focused {
        border-bottom: 1px solid red;
    }
    
    #form2 label.focused {
        border-bottom: 1px solid green;
    }
    

    JS Fiddle demo.

    【讨论】:

      【解决方案3】:

      对于问题 1,使用 $(this) 作为选择器:

      $('input[type="text"]').focus(function() {  
         $(this).css("border-bottom-color", "red");
      });  
      $('input[type="text"]').blur(function() {  
         $(this).css("border-bottom-color", "#e6e6e6");
      });
      

      对于问题 2,您的意思是,在用户选择了这两个项目之后,以任一顺序?它们不能同时聚焦。

      【讨论】:

      • 不不不...看来,你没有得到我的问题。请重新阅读。
      • 每个文本框都有一个标签。我只想更改焦点文本框标签的边框颜色
      • 专注于 1 个文本框,但更改了所有标签的颜色 prntscr.com/3w300 和模糊事件 prntscr.com/3w30v
      • 我有 2 个表格。带有 id 的 form1 和 form2。我想对第二种形式做同样的事情,但颜色会是另一种。如何修改这个函数?
      【解决方案4】:

      您的选择器对于操作 css 不够具体。您必须具体说明要更新的标签。像这样的:

      $('input[type="text"],textarea,input[type="password"]').focus(function() {  
         $("label[for='" + $(this).attr('id') + "']").css("border-bottom-color", "red");
      }); 
      

      【讨论】:

      • 如何修改输入类型文本和密码的函数?
      • 我在上面为你添加了额外的选择器。
      • 我有 2 个表格。带有 id 的 form1 和 form2。我想对第二种形式做同样的事情,但颜色会是另一种。如何修改这个函数?
      猜你喜欢
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多