javascript - 更改事件输入框上的标签颜色

标签 javascript html css

有人知道为什么这不起作用吗? 当框处于事件状态时,我想更改输入框中标签的颜色。

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

JS Fiddle demo .

或者,使用 on()(假设您使用的是 jQuery 1.7 或更高版本):

$('input').on('focus blur', function(e){
    var prev = $(this).prev();
    prev[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});

JS Fiddle demo .

更抽象(因此 HTML 结构无关紧要),通过 for 属性选择:

$('input').on('focus blur', function(e){
    var label = $('label[for="' + this.id + '"]');
    label[e.type == 'focus' ? 'addClass' : 'removeClass']('active');
});

JS Fiddle demo .

引用资料:

关于javascript - 更改事件输入框上的标签颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945291/

相关文章:

javascript - 使用隐藏状态而不是注释或自定义脚本标记来模板化 HTML

html - 水平菜单中的分割线

javascript - 使用 NgRx,在状态对象中重置或返回空数组的正确方法是什么?

javascript - 从js对象获取img源

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

javascript - 滚动溢出时检查视口(viewport)中对象的可见性

html - css 转换在 IE11 中 100% 的时间都不起作用

html - 将变量添加到一组数组

具有数百万个单元格的 HTML 表格会忽略单元格的固定尺寸

html - 将图像放入灵活的 Div 框内而不扭曲图像