<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖动滑块验证</title>
<style type="text/css">
#lu-slide{
width: 300px;
height: 40px;
background-color: #ddd;
text-align: center;
position: relative;
}
#lu-slide #slide{
border:1px solid #000;
width: 40px;
height: 38px;
background-color: #fff;
position: absolute;
top:0;
left:0;
z-index: 10;
}
#lu-slide #text{
line-height: 40px;
}
#lu-slide #bg{
height: 40px;
position: absolute;
top:0;
left: 0;
z-index: 10;
background-color: rgba(100,100,255,0.5);
}
</style>
</head>
<body>
<div id="lu-slide">
<div id='slide'></div><!-- 滑块-->
<p id='text'>拖动滑块验证</p><!--文字 -->
<div id='bg'></div><!--背景 -->
</div>
<script>
window.onload = function (){
var slideBtn = document.getElementById('slide');
var text = document.getElementById('text');
var bg = document.getElementById('bg');
var flag = false;//通过验证标志
slideBtn.onmousedown = function(event){
var mdownX = event.clientX;//鼠标按下的位置
slideBtn.onmousemove = function(e){
var moveLength = e.clientX - mdownX;//滑块移动距离
var maxLength = text.offsetWidth - slideBtn.offsetWidth//滑块移动最大距离
if(moveLength>0){
this.style.left = moveLength + 'px';
bg.style.width = moveLength + 'px';
if(moveLength >= maxLength){
slideBtn.onmousemove = null;//清除事件
slideBtn.onmousedown = null;
text.style.color = '#000';
text.innerText = '通过验证';
flag = true;
}
}
}
}
slideBtn.onmouseup = function(){
if(!flag){
slideBtn.style.left = 0;
bg.style.width = '0px';
slideBtn.onmousemove = null;//没有通过验证只清除鼠标移动事件,可以在次拖动验证
}
}
}
</script>
</body>
</html>