前言
滑块验证码也是生活中常见的,本文会介绍如何实现以及原理。
如果对验证码实现感兴趣的可以看这篇文章:验证码实现 - html页面版
如果对验证码实现感兴趣的可以看这篇文章:验证码实现 - 工具类调用版
代码实现
滑块验证码主要用到几个属性:clientX,screenX,pageX,offsetX。
代码的解释在注释中已经写的很清楚了,如有更好的实现方式欢迎留言。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>滑块验证码</title>
<style>
* {
margin: 0px;
padding: 0px;
font-family: "微软雅黑";
}
.drag {
width: 300px;
height: 40px;
line-height: 40px;
background-color: #e8e8e8;
position: relative;
margin: 0 auto;
}
.bg {
width: 40px;
height: 100%;
position: absolute;
background-color: #75CDF9;
}
.text {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
user-select: none;
}
.btn {
width: 40px;
height: 38px;
position: absolute;
border: 1px solid #ccc;
cursor: move;
font-family: "宋体";
text-align: center;
background-color: #fff;
user-select: none;
color: #666;
}
</style>
</head>
<body>
<div class="drag">
<div class="bg"></div>
<div class="text" onselectstart="return false">请拖动滑块解锁</div>
<div class="btn">>></div>
</div>
<script>
var $ = function (selector) {
return document.querySelector(selector);
},
box = $(".drag"),
bg = $(".bg"),
text = $(".text"),
btn = $(".btn"),
success = false,
distance = box.offsetWidth - btn.offsetWidth;
btn.onmousedown = function (e) {
btn.style.transition = "";
bg.style.transition = "";
var e = e || window.event;
var downX = e.clientX;
document.onmousemove = function (e) {
var e = e || window.event;
var moveX = e.clientX;
var offsetX = moveX - downX;
if (offsetX > distance) {
offsetX = distance;
} else if (offsetX < 0) {
offsetX = 0;
}
btn.style.left = offsetX + "px";
bg.style.width = offsetX + "px";
if (offsetX == distance) {
text.innerHTML = "验证通过";
text.style.color = "#fff";
btn.innerHTML = "√";
btn.style.color = "green";
bg.style.backgroundColor = "lightgreen";
success = true;
btn.onmousedown = null;
document.onmousemove = null;
setTimeout(function () {
alert('解锁成功!');
}, 100);
}
}
document.onmouseup = function (e) {
if (success) {
return;
} else {
btn.style.left = 0;
bg.style.width = 0;
btn.style.transition = "left 1s ease";
bg.style.transition = "width 1s ease";
}
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
</body>
</html>
效果图展示
如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)