使用html+css+js实现发送验证码功能
时间: 2023-12-22 20:03:48 浏览: 52
以下是一个简单的示例代码,用于使用HTML+CSS+JS实现发送验证码功能:
HTML代码:
```html
<form>
<label for="phone">手机号:</label>
<input type="tel" id="phone" name="phone" required>
<button type="button" id="send-code">发送验证码</button>
<br>
<label for="code">验证码:</label>
<input type="text" id="code" name="code" required>
<button type="submit">提交</button>
</form>
```
CSS代码:
```css
form {
display: flex;
flex-direction: column;
align-items: center;
}
input[type="tel"] {
padding: 8px;
margin: 8px;
width: 200px;
border-radius: 4px;
border: 1px solid #ccc;
}
button {
padding: 8px;
margin: 8px;
border-radius: 4px;
border: none;
cursor: pointer;
}
#send-code {
background-color: #4CAF50;
color: white;
}
#send-code:disabled {
background-color: #ccc;
cursor: not-allowed;
}
#code {
width: 100px;
}
```
JS代码:
```js
const phoneInput = document.getElementById('phone');
const sendCodeButton = document.getElementById('send-code');
const codeInput = document.getElementById('code');
let countdown = 60;
let countdownTimer;
function startCountdown() {
countdownTimer = setInterval(() => {
countdown--;
sendCodeButton.textContent = `重新发送 (${countdown}s)`;
if (countdown === 0) {
clearInterval(countdownTimer);
sendCodeButton.textContent = '发送验证码';
sendCodeButton.disabled = false;
countdown = 60;
}
}, 1000);
}
sendCodeButton.addEventListener('click', () => {
// TODO: 发送验证码
sendCodeButton.disabled = true;
startCountdown();
});
document.querySelector('form').addEventListener('submit', (event) => {
event.preventDefault();
// TODO: 提交验证码
});
```
在上面的代码中,我们使用了`input`元素的`type="tel"`属性来限制用户只能输入手机号码。我们还设置了一个计时器来处理重新发送验证码的倒计时。当用户点击发送验证码按钮时,我们会禁用该按钮并开始计时器。当倒计时结束时,我们会重置按钮状态并重新启用该按钮。在表单提交时,我们可以使用相关的代码来验证和提交验证码。注意,这个示例只是一个基本的框架,具体实现可能因需求而异。