<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>图片滑动验证</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> .box { width: 500px; height: 300px; background: url("hauka.png") no-repeat; background-size: 100%; position: relative; margin: auto; } .img { width: 40px; height: 40px; background: url("hauka.png") no-repeat; position: absolute; top: 110px; left: 0px; z-index: 1; } .gap { width: 20px; height: 20px; background-color: red; position: absolute; left: 221px; } .move { width: 40px; height: 40px; background-color: blue; position: absolute; top: 110px; left: 221px; cursor: pointer; } </style> </head> <body> <div> <div class="box"> <div class="img" style="background-position: -221px center"></div> <div class="gap" style="left: 221px"></div> <div class="move"></div> </div> </div> <script> var box = document.querySelector(".box"); var img = document.querySelector(".img"); var gap = document.querySelector(".gap"); var move = document.querySelector(".move"); var initialX = 0; // 初始滑块位置 var isDragging = false; // 标记是否正在拖动滑块 var boxWidth = box.offsetWidth; var imgWidth = img.offsetWidth; // 随机生成图片的缺口 function generateGap() { var left = Math.floor(Math.random() * (boxWidth - 2 * imgWidth)) + imgWidth; gap.style.left = left + "px"; img.style.backgroundPosition = -left + "px center"; initialX = left; return left; } // 拖动事件绑定 move.addEventListener("mousedown", function (e) { isDragging = true; // 标记开始拖动 initialX = e.clientX - parseInt(move.style.left || move.offsetLeft, 10); }); document.addEventListener("mousemove", function (e) { if (isDragging) { var mouseX = e.clientX; // 鼠标相对于文档左边的距离 var moveX = mouseX - box.getBoundingClientRect().left - initialX; // 计算滑块的位置 // 判断是否超出容器边界 if (moveX < 0) { moveX = 0; } else if (moveX > boxWidth - imgWidth) { moveX = boxWidth - imgWidth; } move.style.left = moveX + "px"; } }); document.addEventListener("mouseup", function (e) { if (isDragging) { isDragging = false; // 标记结束拖动 var imgLeft = parseInt(img.style.left); var gapLeft = parseInt(gap.style.left); // 判断滑块是否与缺口重合 if (Math.abs(imgLeft - gapLeft) < 5) { alert("验证成功!"); } else { alert("验证失败,请重新尝试。"); generateGap(); // 重新生成缺口 move.style.left = "0px"; // 将滑块重置到起始位置 } } }); // 页面加载时生成缺口 generateGap(); </script> </body> </html>
标签:style,img,验证,代码,move,moveX,var,滑动,left From: https://www.cnblogs.com/fgxwan/p/17693906.html