如何将onfocus事件侦听器添加到输入字段以更改标签的样式

问题描述 投票:1回答:1

当我在输入字段上使用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;
           }
javascript html forms events javascript-events
1个回答
0
投票

也不要忘记在模糊时删除您喜欢的类

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>
© www.soinside.com 2019 - 2024. All rights reserved.