2011-11-06 62 views
0

我的jQuery函數看起來像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。我想做同樣的事情來第二種形式,但顏色將是另一種。如何修改這個func?

我的形式看起來就像是

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

回答

1

這把小提琴怎麼樣?

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

label標籤的for屬性引用到inputid屬性,而不是它的name。 我也將樣式移至CSS。

+0

如何修改輸入類型文本和密碼的這個func? –

+0

很簡單:$('input [type =「text」],input [type =「password」]')或者使用$('input')...如果可以的話。 – biziclop

+0

和我的第二個問題? –

0

問題1,使用$(本)爲您的選擇:

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

對於問題2,你的意思是,用戶選擇後兩個項目,以任何順序?他們不能同時關注。

+0

不,不,不......看來,你不明白我的問題。請重新閱讀。 –

+0

每個文本框都有一個標籤。而我想改變只有集中的文本框label'sborder顏色 –

+0

專注於1文本框,但改變了所有標籤http://prntscr.com/3w300和模糊事件的顏色http://prntscr.com/3w30v –

0

您的選擇器不足以操縱css。您必須具體說明要更新哪個標籤。事情是這樣的:

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

如何修改輸入類型文本和密碼的這個func? –

+0

我在上面爲您添加了其他選擇器。 – danpickett

+0

我有2種形式。用id的form1和form2。我想做同樣的事情來第二種形式,但顏色將是另一種。如何修改這個func? –

1

使用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