2017-10-13 51 views
0

我有两个输入框内的绝对位置div。还有这些输入框上的标签。我想要的效果是,当我关注一个输入框时,标签应该是蓝色,当模糊时应该去掉该类(蓝色)。同时还有另一个标签和输入框。如何在纯javascript中改变输入焦点上的标签颜色?

// Initial color of label 
 
label.labels{ 
 
    color: black; 
 
} 
 

 
input.box{ 
 
    border-width: 0 0 2px 0; 
 
    outline: none; 
 
}
<div style = "position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;"> 
 
    <label class = "labels">First Name:</label> 
 
    <input type = "text" class = "box" /><br /> 
 
    <label class = "labels">Last Name:</label> 
 
    <input type = "text" class = "box" /> 
 
</div>

当我聚焦input.box然后label.labels颜色应该是蓝色。而且,输入和标签都具有相同的类别。如何用纯Javascript实现这种效果?或者如果可能的话,请告诉我如何用CSS实现这一点?

+0

[你可能有兴趣在':focus'伪类(HTTPS ://developer.mozilla.org/en-US/docs/Web/CSS/:focus) – castis

+0

不工作的兄弟! – Sanjay

+0

你想同时影响**两个**标签吗? –

回答

2

下面是使用纯JavaScript的解决方案:

function toggleClass() { 
 
    this.previousElementSibling.classList.toggle('imblue'); 
 
} 
 

 
var inputs = document.getElementsByClassName('box'); 
 

 
for (var i = 0; i < inputs.length; i++) { 
 
    var input = inputs[i]; 
 

 
    input.addEventListener('focus', toggleClass); 
 
    input.addEventListener('blur', toggleClass); 
 
}
label.labels { 
 
    color: black; 
 
} 
 

 
input.box { 
 
    border-width: 0 0 2px 0; 
 
    outline: none; 
 
} 
 

 
.imblue { 
 
    color: blue !important; 
 
}
<div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;"> 
 
    <label class="labels">First Name:</label> 
 
    <input type="text" class="box" /><br /> 
 
    <label class="labels">Last Name:</label> 
 
    <input type="text" class="box" /> 
 
</div>

+0

就是这样!非常感谢! – Sanjay

+0

哇!难以置信的!看起来我需要深入Java脚本。 – Sanjay

4

使用:focus-within伪元素的css解决方案。请注意,这在IE/Edge中不受支持。

您需要将每个labelinput对包装起来才能使用。

// Initial color of label 
 
label.labels { 
 
    color: black; 
 
} 
 

 
input.box { 
 
    border-width: 0 0 2px 0; 
 
    outline: none; 
 
} 
 

 
.field:focus-within .labels { 
 
    color: blue; 
 
}
<div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;"> 
 
    <div class="field"> 
 
    <label class="labels">First Name:</label> 
 
    <input type="text" class="box" /><br /> 
 
    </div> 
 
    <div class="field"> 
 
    <label class="labels">Last Name:</label> 
 
    <input type="text" class="box" /> 
 
    </div> 
 
</div>

+1

这是一个很好的解决方案。请记住,它不是普遍支持:http://caniuse.com/#search=focus-within – wlh

+0

是啊!因为它不被所有浏览器支持。对不起,我不能接受这个答案。但这是一个很好的解决方案! – Sanjay

相关问题