有人知道为什么这不起作用吗? 当框处于事件状态时,我想更改输入框中标签的颜色。
JavaScript:
$("input").focus(function() {
var inputID = document.activeElement.id;
document.getAnonymousElementByAttribute('label','for', inputID).setAttribute('class', 'active');
});
HTML:
<label for="username">Username</label>
<input name="username" id="username" type="text"><br>
<label for="passwort">Passwort</label>
<input name="passwort" id="passwort" type="password"><br>
<input type="submit" class="button" value="login">
CSS:
.active{
color: #FFA500 !important;
}
我希望有人能帮助我:)
最佳答案
使用您当前的 HTML:
$('input').focus(function(){
$(this).prev().addClass('active');
}).blur(function(){
$(this).prev().removeClass('active');
});
或者,使用 on()
(假设您使用的是 jQuery 1.7 或更高版本):
$('input').on('focus blur', function(e){
var prev = $(this).prev();
prev[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});
更抽象(因此 HTML 结构无关紧要),通过 for
属性选择:
$('input').on('focus blur', function(e){
var label = $('label[for="' + this.id + '"]');
label[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});
引用资料:
- >
addClass()
. - > Attribute-equals (
[attribute="value"]
) selector . - >
blur()
. - >
focus()
. - >
on()
. - >
prev()
. - >
removeClass()
.
关于javascript - 更改事件输入框上的标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945291/