当我在输入字段上使用onfocus时,我试图使输入标签的样式更改为.fancyclass样式。我想知道如何使用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;
}
也不要忘记在模糊时删除您喜欢的类
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>