原生JS實現拖動滑塊驗證登錄效果


♀分享一組利用原生JS實現拖動滑塊驗證效果

♀在這個組代碼中涉及三個方面的知識:

⑴事件處理

⑵添加驗證標記

⑶選擇器的封裝

 

代碼如下:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>驗證碼</title> <style> .box{ position:relative; width: 200px; height: 40px; background: #CCC; display: block; margin:150px auto; } .btn{ background:#EEE url(1.png) no-repeat; background-position: center center; position:absolute; top:0; width: 40px; height: 40px; z-index: 3; line-height:40px; } .text{ position: absolute; width: 100%; margin: 0; line-height:40px; text-align: center; z-index: 2; } .bg{ position: absolute; height: 100%; background-color: #7ac23c; z-index: 1; } </style> </head> <body> <div class="box"> <!-- 滑塊 --> <div class="btn"></div> <!-- 文字 --> <p class="text">請向右滑動滑塊</p> <!-- 背景 --> <div class="bg"></div> </div> <script> window.onload = function(){ //選擇器封裝 var fun2 = function(name){//函數表達式 return document.querySelector(name); }; var btn = fun2(".btn"),//按鈕  box = fun2(".box"),//盒子  text = fun2(".text"),//文字  bg = fun2(".bg"),//背景  flag = false;//驗證失敗 //鼠標按下 //event 對象 事件的狀態  btn.onmousedown = function(event){ var e = event || window.event; var downX = e.clientX; //按下與X軸的點 //移動  btn.onmousemove = function(event){ var moveX = event.clientX - downX; //移入的距離-按下的距離 //移動范圍 if(moveX > 0){ this.style.left = moveX + 'px'; bg.style.width = moveX + 'px'; //驗證成功 if(moveX >= (box.offsetWidth - this.offsetWidth)){ flag = true; //'驗證成功'  text.innerHTML = '驗證成功'; text.style.color = '#fff'; btn.onmousemove = null; //清除事件  btn.onmousedown = null; //清除事件  } } }; }; //松開  btn.onmouseup = function(){ btn.onmousemove = null; //清除事件 //判斷條件 if(flag) return; this.style.left = 0; bg.style.width = 0; } } </script> </body> </html>

 

效果圖:

 

 

參考:https://www.bilibili.com/video/av75439023


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM