如图所示,期望实现下图效果
当input框聚焦时,提示词上移且样式改变,如果input输入了值,则提示词不还原位置,如果不存在,提示词还原位置。
思路:
- 移动词为label,当input.onfocus时,label增加active样式,增加上移动画,当input.onblur时,还原样式
- 判断输入框是否输入了值,如果输入了,则label增加样式,如果为空,则还原样式。
- 分别有两种实现方式
1.通过css的伪类属性实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>register</title>
<style>
.item {
position: relative;
margin-top: 10px;
width: 200px;
}
.item label {
position: absolute;
top: calc((30px - 16px)/2);
left: 50px;
font-size: 16px;
/*这个属性的默认值是auto 默认是这个元素可以被点击
但是如果我们写了none 就是这个元素不能被点击,就好像它可见但是不能用
可望而不可及*/
pointer-events: none;
transition: all 0.5s;
}
.item input {
border-radius: 5px;
width: 100%;
border: 1px solid black;
outline: none;
height: 30px;
padding-left: 10px
}
.item input:focus + label,
.item input:valid + label {
top: -6px;
font-size: 12px;
color: goldenrod;
background: white;
}
</style>
</head>
<body>
<!-- 此种方式下,必须是input在前,label在后 -->
<div class="register" style="margin: 100px;">
<div class="item">
<input type="text" autocomplete="off" id="tel" required name="tel" value="">
<label for="tel">手机号码</label>
</div>
<div class="item">
<input type="password" autocomplete="off" id="pwd" required name="pwd" value="">
<label for="pwd">密码</label>
</div>
</div>
</body>
</html>
2. 通过css+js实现,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
@keyframes toTop {
from {
top: calc((30px - 16px)/2);
}
to {
top: -12px;
}
}
.item {
margin-top: 30px;
position: relative;
height: 30px;
width: 200px;
}
input {
width: 100%;
height: 30px;
border: 1px solid black;
outline: none;
border-radius: 5px;
}
.item label {
position: absolute;
top: calc((30px - 16px)/2);
left: 20px;
background: white;
animation-fill-mode: forwards;
/* 保留动画最后的位置 */
}
.labelActive {
animation-name: toTop;
animation-duration: 1s;
font-size: 12px;
color: goldenrod;
}
</style>
</head>
<body>
<form class="login">
<div class="item">
<label for="tel">手机号码</label>
<input type="text" id="tel" autocomplete="off" value="" name="tel">
</div>
<div class="item">
<label for="password">密码</label>
<input type="password" id="password" autocomplete="off" value="" name="password">
</div>
</form>
<script>
// 添加:document.getElementById("id").classList.add("className");
// 删除:document.getElementById("id").classList.remove("className");
let inputArr = document.getElementsByTagName('input');
for(let i =0; i<inputArr.length; i++) {
inputArr[i].onfocus = function() {
this.previousElementSibling.classList.add("labelActive");
};
inputArr[i].onblur = function() {
if(this.value == '') {
this.previousElementSibling.classList.remove("labelActive")
}
}
}
</script>
</body>
</html>