先看效果图:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/129.css">
</head>
<body>
<!-- 滑动拼图结构 -->
<div class="box">
<div class="check">
<div class="check-content"></div>
<div class="check-block"></div>
</div>
<div class="drag">
<div class="drag-block"></div>
<div class="drag-tips">按住左边按钮向右拖动完成上方图像验证</div>
</div>
</div>
</body>
<script src="/129.js"></script>
</html>
CSS:
/* 初始化样式 + 容器大小 + 拼图背景 */
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
width: 375px;
margin: 100px auto;
}
.check {
width: 375px;
height: 250px;
background-size: 100% 100%;
background-image: url('https://t7.baidu.com/it/u=1303147949,3993366089&fm=193&f=GIF');
}
/* 拼图空缺容器样式 */
.check-content {
position: absolute;
top: 100px;
left: 280px;
width: 50px;
height: 50px;
background: rgba(0, 0, 0, 0.5);
border: 1px solid #fff;
}
/* 拼图填充容器样式 */
.check-block {
width: 50px;
height: 50px;
border: 1px solid #fff;
background-image: inherit;
background-repeat: inherit;
background-size: 375px 250px;
background-position: -280px -100px;
position: absolute;
top: 100px;
left: 10px;
}
/* 滑块容器样式 */
.drag {
width: 375px;
height: 50px;
background-color: #e3e3e3;
margin-top: 10px;
position: relative;
}
/* 滑块本体样式 */
.drag-block {
width: 50px;
height: 50px;
background-color: yellowgreen;
z-index: 10;
position: absolute;
top: 0;
left: 0;
}
/* 文字提示样式 */
.drag-tips {
width: 95%;
height: 100%;
margin: 0 auto;
text-align: center;
line-height: 50px;
font-size: 12px;
color: #8a8a8a;
}
JS:
//获取校验区域
const drag = document.querySelector('.drag');
//获取两个滑块和拖动按钮
//获取DOM对象
const dragBlock = document.querySelector('.drag-block');
const content = document.querySelector('.check-content');
const check = document.querySelector('.check-block');
//随机生成一个x,y坐标,用于设置校验块的位置
let x = parseInt(Math.random() * 325);
let y = parseInt(Math.random() * 200);
//定义个运动状态 如果为true代表鼠标已经按下
let animating = false;
//存储鼠标按钮的x坐标
let startX = 0;
//存储移动的位置
let offsetX = 0;
//设置拼图随机位置
content.style.cssText = `left:${x}px; top:${y}px;`;
check.style.cssText = `background-position: -${x}px -${y}px; top:${y}px`;
//添加 注册鼠标移动事件
dragBlock.addEventListener('mousemove', e => {
e.preventDefault(); // 阻止默认行为
//判断运动状态
if (!animating) { return };
//计算移动的位置
offsetX = e.pageX - startX;
//判断移动距离是否正确
if (offsetX < 0 || offsetX > 350) { return };
//修改可移动盒子的X轴坐标
dragBlock.style.transform = `translateX(${offsetX}px)`;
//设置被验证滑块left值
check.style.left = `${offsetX}px`;
})
//添加鼠标按下事件
dragBlock.addEventListener('mousedown', (e) => {
animating = true;
startX = e.pageX;
})
//添加鼠标弹出事件
document.addEventListener('mouseup', () => {
animating = false;
//根据移动的位置判断是否成功
if (offsetX >= x - 2 && offsetX <= x + 2) {
alert('验证成功')
} else {
//验证失败 滑块和被验证块恢复坐标
dragBlock.style.transform = 'translateX(0px)';
check.style.left = `0px`;
}
// 重置 offsetX
offsetX = 0;
})