2017-10-13 62 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

相關問題