返回
用 JavaScript 实现获取验证码(模仿百度搜索框样式)
前端
2023-10-13 15:50:14
在当今数字时代,验证码已成为互联网安全中不可或缺的一部分。作为一种用户验证措施,验证码可以有效防止恶意攻击和垃圾邮件。本文将介绍如何使用 JavaScript 实现验证码功能,并将其样式模仿成百度搜索框的样式。
JavaScript 验证码生成
1. 创建画布
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
2. 设置画布大小
canvas.width = 100;
canvas.height = 40;
3. 绘制背景
ctx.fillStyle = '#f0f0f0';
ctx.fillRect(0, 0, canvas.width, canvas.height);
4. 绘制验证码
ctx.font = '20px Arial';
ctx.fillStyle = '#000';
ctx.fillText('ABCDEF', 20, 25);
5. 绘制干扰线
for (var i = 0; i < 10; i++) {
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.strokeStyle = '#ccc';
ctx.stroke();
}
模仿百度搜索框样式
1. 创建输入框
<input type="text" id="captcha">
2. 创建验证码图像
<img src="captcha.png" id="captcha-image">
3. 设置输入框和验证码图像的样式
#captcha {
width: 100px;
height: 40px;
padding: 5px;
border: 1px solid #ccc;
}
#captcha-image {
width: 100px;
height: 40px;
margin-left: 5px;
}
4. 添加点击事件,刷新验证码
document.getElementById('captcha-image').addEventListener('click', function() {
document.getElementById('captcha-image').src = 'captcha.php?' + Math.random();
});
总结
通过以上步骤,我们就成功地用 JavaScript 实现了一个验证码功能,并将其样式模仿成了百度搜索框的样式。这个验证码功能可以有效地防止恶意攻击和垃圾邮件,并为用户提供一个安全的上网环境。