我试图在输入字段上使用.fancyclass
时将输入标签的样式更改为onfocus
样式。我想知道如何在Javascript中使用事件监听器来做到这一点?
<fieldset name="in-fields">
<section>
<label for ="inputname" class="name">Name*</label>
First: <br><input type="text" name="info" required><br/>
Last: <br><input type="text" name="info" required><br/>
</section>
<section>
<label for="inputnumber" class ="name">Phone Number*</label>
<input type="text" name="info" required>
</section>
<section>
<label for="inputemploy" class ="name">Current Employer</label>
<input type="text" name="info">
</section>
<section>
<label for="inputemail" class= "name">Email*</label>
<input type="email" name="info" required>
</section>
</fieldset>
.fancyclass {
font-weight:bold;
text-transform:uppercase;
}
document.querySelectorAll('input[name="info"]').forEach(item=> {
item.addEventListener('focus', event => {
console.log("add fancy class");
})
})
这就是我到目前为止所拥有的...我很确定这是错误的。当我专注于输入字段时,我不知道如何向标签添加花式类。
最佳答案
别忘了在模糊时删除您喜欢的类
const myForm = document.getElementById('my-form')
, All_Labels = myForm['in-fields'].querySelectorAll('label')
;
myForm['in-fields'].querySelectorAll('input').forEach(inElm=>
{
inElm.onfocus=focusOn;
inElm.onblur=focusOff;
})
function focusOn(e)
{
let label_elm = e.target.parentNode.querySelector('label')
All_Labels.forEach(lbl=>
{
if (lbl===label_elm) { lbl.classList.add('fancyclass') }
else { lbl.classList.remove('fancyclass') }
})
}
function focusOff(e)
{
All_Labels.forEach(lbl=> lbl.classList.remove('fancyclass') )
}
.fancyclass {
font-weight:bold;
text-transform:uppercase;
}
<form id="my-form">
<fieldset name="in-fields">
<section>
<label class="name">Name*</label><br>
First: <br><input type="text" name="First-Name" required><br>
Last: <br><input type="text" name="Last-Name" required><br>
</section>
<section>
<label class="name">Phone Number*</label>
<input type="text" name="Phone-Number" required>
</section>
<section>
<label class="name">Current Employer</label>
<input type="text" name="Current-Employer">
</section>
<section>
<label class="name">Email*</label>
<input type="email" name="Email" required>
</section>
</fieldset>
</form>