原生js实现验证码
时间: 2024-01-22 18:19:47 浏览: 136
可以使用原生 JavaScript 实现验证码。以下是一个简单的例子:
HTML:
```html
<label for="captcha">验证码:</label>
<input type="text" id="captcha">
<canvas id="captchaCanvas"></canvas>
<button id="refreshCaptcha">刷新验证码</button>
```
JavaScript:
```javascript
var canvas = document.getElementById("captchaCanvas");
var ctx = canvas.getContext("2d");
// 生成随机验证码
function generateCaptcha() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var captchaLength = 6;
var captcha = "";
for (var i = 0; i < captchaLength; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
return captcha;
}
// 绘制验证码
function drawCaptcha() {
var captcha = generateCaptcha();
canvas.width = 100;
canvas.height = 40;
ctx.font = "bold 20px sans-serif";
ctx.fillStyle = "#000";
ctx.fillText(captcha, 25, 25);
// 添加干扰线
for (var i = 0; i < 5; i++) {
ctx.beginPath();
ctx.moveTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height));
ctx.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height));
ctx.strokeStyle = "#000";
ctx.stroke();
}
return captcha;
}
// 刷新验证码
document.getElementById("refreshCaptcha").addEventListener("click", function() {
var captchaInput = document.getElementById("captcha");
captchaInput.value = "";
var captcha = drawCaptcha();
});
// 验证输入的验证码是否正确
document.getElementById("captcha").addEventListener("input", function() {
var captchaInput = document.getElementById("captcha");
if (captchaInput.value.length == 6 && captchaInput.value.toUpperCase() == captcha) {
alert("验证码正确!");
}
});
```
这个例子首先定义了一个 `generateCaptcha` 函数来生成随机的验证码,然后定义了一个 `drawCaptcha` 函数来绘制验证码,并在验证码中添加了一些干扰线以增加难度。最后使用 `addEventListener` 为刷新按钮和验证码输入框添加事件监听器。
阅读全文