【发布时间】:2021-02-11 02:55:47
【问题描述】:
我只是在学习 JavaScript,还没有找到解决这个问题的任何 vanilla JS 解决方案。我正在研究一个浮动标签表单组,其中输入的标签'隐藏'在输入后面。我希望它通过切换类“form-group-with-value”在输入中有文本时上升。 我不知道任何jQuery,我想避免它。 这是我的代码: P.S:当输入成为焦点时,我设法切换了一个类(以更改标签的颜色)。虽然它确实不是最好的解决方案,但它可以按原样工作。
//Dynamic Form Label
const input = document.querySelectorAll('.custom-input');
const formGroup = document.querySelectorAll('.form-group');
//Toggle color when input is in focus
input[0].addEventListener('focus', () => formGroup[0].classList.toggle('form-group-with-focus') );
input[0].addEventListener('blur', () => formGroup[0].classList.toggle('form-group-with-focus') );
input[1].addEventListener('focus', () => formGroup[1].classList.toggle('form-group-with-focus') );
input[1].addEventListener('blur', () => formGroup[1].classList.toggle('form-group-with-focus') );
input[2].addEventListener('focus', () => formGroup[2].classList.toggle('form-group-with-focus') );
input[2].addEventListener('blur', () => formGroup[2].classList.toggle('form-group-with-focus') );
input[3].addEventListener('focus', () => formGroup[3].classList.toggle('form-group-with-focus') );
input[3].addEventListener('blur', () => formGroup[3].classList.toggle('form-group-with-focus') );
//Toggle label position when input has value
.form-group{
position: relative;
min-height: 50px;
}
.form-group label{
position: absolute;
z-index: -1;
transition: 0.3s;
left: 5px;
}
.form-group-with-focus label{
color: red;
}
.form-group-with-value label{
transform: translateY(-80%);
}
<div class="form-group ">
<label>Full Name</label>
<input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>
<div class="form-group ">
<label>Full Name</label>
<input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>
<div class="form-group ">
<label>Full Name</label>
<input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>
<div class="form-group ">
<label>Full Name</label>
<input type="text" class="form-control custom-input" id="name" placeholder="Full Name">
</div>
请见谅,我是初学者
【问题讨论】:
标签: javascript html css forms function