js实现滑块验证码
滑块验证码的基本原理
滑块验证码是一种常见的人机验证方式,用户需要拖动滑块到指定位置完成验证。核心逻辑包括生成滑块、验证拖动位置、以及后端校验。
实现步骤
HTML 结构
<div class="slider-captcha">
<div class="slider-track"></div>
<div class="slider-thumb"></div>
<div class="slider-mask"></div>
</div>
CSS 样式
.slider-captcha {
position: relative;
width: 300px;
height: 40px;
background: #f0f0f0;
border-radius: 20px;
}
.slider-thumb {
position: absolute;
width: 40px;
height: 40px;
background: #4CAF50;
border-radius: 50%;
cursor: grab;
z-index: 2;
}
.slider-mask {
position: absolute;
width: 0;
height: 40px;
background: #8BC34A;
border-radius: 20px;
}
JavaScript 逻辑
const thumb = document.querySelector('.slider-thumb');
const mask = document.querySelector('.slider-mask');
let isDragging = false;
let startX = 0;
let thumbX = 0;
thumb.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.clientX;
thumbX = thumb.offsetLeft;
thumb.style.cursor = 'grabbing';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const deltaX = e.clientX - startX;
let newX = thumbX + deltaX;
const maxX = 300 - 40; // 容器宽度 - 滑块宽度
// 限制滑块移动范围
newX = Math.max(0, Math.min(newX, maxX));
thumb.style.left = `${newX}px`;
mask.style.width = `${newX}px`;
});
document.addEventListener('mouseup', () => {
if (!isDragging) return;
isDragging = false;
thumb.style.cursor = 'grab';
// 验证是否拖动到目标位置(例如最后20px范围内)
const thumbLeft = thumb.offsetLeft;
if (thumbLeft >= 260) {
alert('验证成功');
} else {
thumb.style.left = '0px';
mask.style.width = '0px';
}
});
进阶优化
随机目标位置
const targetPos = Math.floor(Math.random() * 260) + 20;
// 验证时判断是否在目标位置附近
if (Math.abs(thumbLeft - targetPos) < 10) {
alert('验证成功');
}
添加背景图案 可在滑块轨道上添加缺口图案,用户需要将滑块拖动到缺口位置。
后端校验 前端验证后,应将滑动轨迹、时间等数据发送到后端进行二次验证,防止模拟攻击。

注意事项
- 移动端需添加
touchstart/touchmove事件支持 - 可增加滑动轨迹分析,防止机器人模拟
- 避免使用固定阈值,增加随机性
- 生产环境建议使用成熟库如 Geetest 等
以上代码实现了基础滑块验证功能,实际应用中需根据安全需求进一步完善。






