失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > html滑动验证图片 纯js实现图片滑块验证

html滑动验证图片 纯js实现图片滑块验证

时间:2018-06-28 15:16:22

相关推荐

html滑动验证图片 纯js实现图片滑块验证

需求:js实现滑块验证

思路:设置position:absolute,通过left值控制滑动

再来说几个js事件:

onmousedown

事件会在鼠标按键被按下时发生

onmousemove

事件会在鼠标指针移动时发生

onmouseup

事件会在鼠标松开时发生

实现:

//完成图片及滑块的摆放

请拖动滑块解锁>>

及样式:

.box {

width: 311px;

height:155px;

margin:0 auto;

position:relative;

}

.inner {

position:absolute;

left:0;

}

.drag{

width: 311px;

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;

}

写完后是这样滴:

接下来写事件:

首先获取滑动键被点了

btn.onmousedown = function(e){

var e = e || window.event;

//鼠标点的位置

var downX = e.clientX;

}

监听移动事件(写在点击方法里面,这里为了方便介绍,可下载源码):

document.onmousemove = function(e){

var e = e || window.event;

//获取鼠标移动后的水平位置

var moveX = e.clientX;

//获取移动了多少

offsetX = moveX - downX;

//防止越界

if( offsetX > distance){

offsetX = distance;//如果滑过了终点,就将它停留在终点位置

}else if( offsetX < 0){

offsetX = 0;//如果滑到了起点的左侧,就将它重置为起点位置

}

//根据移动距离让按钮,小图片及背景色动起来

按钮.style.left = offsetX + "px";

背景.style.width = offsetX + "px";

小图.style.left=offsetX + "px";

}

然后通过移动距离和需要的距离做对比,获取状态。

if( offsetX == "目标"){

//1.设置滑动成功后的样式

text.innerHTML = "";

text.style.color = "#fff";

btn.innerHTML = "√";

btn.style.color = "green";

bg.style.backgroundColor = "lightgreen";

success=true;

//2.成功后,清除掉鼠标按下事件和移动事件(因为移动时并不会涉及到鼠标松开事件)

btn.onmousedown = null;

document.onmousemove = null;

//3.成功解锁后的回调函数

setTimeout(function(){

alert('解锁成功!');

},100);

}

当鼠标松开时:

document.onmouseup = function(e){

//如果鼠标的水平移动距离 = 滑动成功的宽度

if( success){

return;

}else{

//反之,则将滑块复位(设置了1s的属性过渡效果)

btn.style.left = 0;

bg.style.width = 0;

inner.style.left=0;

btn.style.transition = "left 1s ease";

inner.style.transition = "left 1s ease";

bg.style.transition = "width 1s ease";

}

//只要鼠标松开了,说明此时不需要拖动滑块了,那么就清除鼠标移动和松开事件。

document.onmousemove = null;

document.onmouseup = null;

}

大体实现思路就这些啦!

源码地址:/myweiwei/S...

将不断更新完善,期待您的批评指正!

如果觉得《html滑动验证图片 纯js实现图片滑块验证》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。