js实现滑块解锁
效果图1:
效果图2:
<!DOCTYPE html> <html> <head> <title>滑块验证</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> #container{ padding: 0; margin: 0; position: relative; width:350px; height: 50px; border: 1px solid gray; border-radius: 3px; margin: 10px auto; line-height: 50px; user-select:none; } #success,#mark,#move{ position: absolute; width: 100%; height: 100%; font-size: 20px; font-weight: bold; text-align: center; color: white; } #success{ background: lightgreen; } #mark{ background:gray; } #move{ width: 50px; background: white; color: black; top: 0; left: 0; cursor: move; } </style> </head> <body> <div id="container"> <div id="success">success!</div> <div id="mark">please,slide!</div> <div id="move">>></div> </div> <script type="text/javascript"> let move=document.getElementById('move'), mark=document.getElementById('mark'), container=document.getElementById('container'), distance=container.getBoundingClientRect().width,//总长度 isstop=false,//是否到达终点 offL=container.offsetLeft,//容器左边距 moveL=null,//滑块左边距 scale=null;//渐变进度 move.onmousedown=function(event){ move.onmousemove=function(event){ move.style.transform=''; moveL=event.clientX-offL-25,//让鼠标在滑块中间 scale=((moveL+25)/3.5)+'%';//左边距和总长度比率 if(moveL>distance-50){ isstop=true; return;//返回不再执行下面的语句 } move.style.setProperty('left',moveL+'px'); mark.style.setProperty('background',`linear-gradient(to right, lightblue 0%, lightblue ${scale}, gray ${scale}, gray 100%)`); } } document.onmouseup=function(){//move不准确 if(isstop){ mark.style.setProperty('display','none'); move.innerText='√' setTimeout(()=>{alert('success!')},200); move.onmousedown=null; move.onmousemove=null; document.onmouseup=null; }else{ move.style.transform=`translateX(${-moveL}px)`; mark.style.background='gray'; //mark.style.transition='all .5s';//因颜色过渡出现了底层的青色 move.onmousemove=null; } } </script> </body> </html>
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦