js注册表单特效
时间: 2023-07-23 21:05:18 浏览: 39
以下是一个简单的注册表单特效的示例,实现了以下功能:
1. 当输入框聚焦时,标签会上移并缩小。
2. 当输入框失焦时,如果输入框内没有内容,则标签恢复原位。
3. 当输入框有内容时,右侧会出现清空按钮。
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册表单特效</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #f2f2f2;
font-family: Arial, Helvetica, sans-serif;
}
.container {
max-width: 500px;
margin: 50px auto;
background-color: #fff;
padding: 30px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 5px;
}
h2 {
margin-bottom: 20px;
color: #333;
}
form {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.form-group {
flex: 1 0 calc(50% - 10px);
margin-bottom: 20px;
position: relative;
}
.form-group label {
position: absolute;
top: 0;
left: 10px;
color: #999;
font-size: 16px;
line-height: 20px;
transition: all 0.3s;
}
.form-group input {
width: 100%;
padding: 10px;
border: none;
border-bottom: 2px solid #999;
background-color: transparent;
font-size: 16px;
color: #333;
}
.form-group input:focus + label {
top: -20px;
font-size: 14px;
color: #333;
}
.form-group input:not(:placeholder-shown) + label {
top: -20px;
font-size: 14px;
color: #333;
}
.form-group .clear-btn {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
display: none;
cursor: pointer;
}
.form-group .clear-btn:hover {
color: #f00;
}
.form-group input:not(:placeholder-shown) ~ .clear-btn {
display: block;
}
</style>
</head>
<body>
<div class="container">
<h2>注册表单</h2>
<form>
<div class="form-group">
<input type="text" id="username" placeholder=" " required>
<label for="username">用户名</label>
<div class="clear-btn" onclick="clearInput('username')">X</div>
</div>
<div class="form-group">
<input type="email" id="email" placeholder=" " required>
<label for="email">邮箱</label>
<div class="clear-btn" onclick="clearInput('email')">X</div>
</div>
<div class="form-group">
<input type="password" id="password" placeholder=" " required>
<label for="password">密码</label>
<div class="clear-btn" onclick="clearInput('password')">X</div>
</div>
<div class="form-group">
<input type="password" id="confirm-password" placeholder=" " required>
<label for="confirm-password">确认密码</label>
<div class="clear-btn" onclick="clearInput('confirm-password')">X</div>
</div>
<div class="form-group">
<button type="submit">注册</button>
</div>
</form>
</div>
<script>
function clearInput(id) {
document.getElementById(id).value = '';
document.getElementById(id).focus();
document.querySelector(`label[for="${id}"]`).style.top = '0';
document.querySelector(`label[for="${id}"]`).style.fontSize = '16px';
document.querySelector(`label[for="${id}"]`).style.color = '#999';
}
</script>
</body>
</html>
```
注意:该示例仅包含基本功能,实际使用时需要根据具体需求进行修改和完善。