JavaScript實現(xiàn)滑塊驗證解鎖
更新時間:2021年01月07日 16:06:34 作者:努力的黑皮
這篇文章主要為大家詳細介紹了JavaScript實現(xiàn)滑塊驗證解鎖,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了JavaScript實現(xiàn)滑塊驗證解鎖的具體代碼,供大家參考,具體內(nèi)容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> // 引入矢量圖標(biāo)庫 <link rel="stylesheet" > <title>Document</title> <style> * { margin: 0; padding: 0; } .box { width: 300px; height: 40px; line-height: 40px; text-align: center; background-color: #e8e8e8; box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2); position: relative; margin-top: 100px; margin-left: 200px; } .box .bgColor { position: absolute; left: 0; top: 0; width: 40px; height: 40px; } .box .tips { position: absolute; width: 100%; height: 40px; line-height: 40px; font-size: 14px; color: #000; text-align: center; user-select: none; } .ball { width: 50px; height: 38px; border: 1px solid #ccc; background: #fff; text-align: center; cursor: move; position: absolute; top: 0; left: 0; } </style> </head> <body> <div class="box"> <div class="bgColor"></div> <div class="tips">滑動驗證</div> <div class="ball"><i class="iconfont icon-double-arro-right"></i></div> </div> </body> <script> var box = document.getElementsByClassName("box")[0]; var ball = document.getElementsByClassName("ball")[0]; var bgColor = document.getElementsByClassName("bgColor")[0]; var tips = document.getElementsByClassName("tips")[0]; // 設(shè)置成功狀態(tài) var isSuccess = false; //默認為false 不成功 ball.onmousedown = function(e) { var e = e || window.event; // 獲取鼠標(biāo)相對于事件源左上角的位置 var posx = e.offsetX; // 每次鼠標(biāo)按下時 清除動畫樣式 ball.style.transition = ""; bgColor.style.transition = ""; document.onmousemove = function(e) { var e = e || window.event; var x = e.pageX - box.offsetLeft - posx; var max = box.clientWidth - ball.clientWidth; if (x <= 0) { x = 0; } if (x >= max) { x = max; } bgColor.style.width = x + "px"; ball.style.left = x + "px"; bgColor.style.backgroundColor = "#6ff"; if (x == max) { success(); } } document.onmouseup = function() { // 如果沒有解鎖成功則返回原點 if (!isSuccess) { bgColor.style.width = 0 + "px"; ball.style.left = 0 + "px"; ball.style.transition = "left 0.6s linear"; bgColor.style.transition = "width 0.6s linear"; } // 鼠標(biāo)抬起時,移除鼠標(biāo)移動事件和鼠標(biāo)抬起事件 document.onmouseup = null; document.onmousemove = null; } } // 定義一個滑塊解鎖成功的方法 function success() { isSuccess = true; // 獲取圖標(biāo) var icon = ball.firstElementChild; tips.textContent = "解鎖成功"; bgColor.style.backgroundColor = "lightgreen"; icon.className = "iconfont icon-gou"; icon.style.color = "lightgreen"; //滑動成功時,移除鼠標(biāo)按下事件 ball.onmousedown = null; } </script> </html>
效果圖如下:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS和css實現(xiàn)檢測移動設(shè)備方向的變化并判斷橫豎屏幕
這篇文章主要介紹了JS和css實現(xiàn)檢測移動設(shè)備方向的變化并判斷橫豎屏幕,本文分別給出實現(xiàn)代碼,需要的朋友可以參考下2015-05-05JavaScript中日期函數(shù)的相關(guān)操作知識
日期函數(shù)是我們經(jīng)常用到的知識點,下面通過本文給大家介紹JavaScript中日期函數(shù)的相關(guān)操作知識,非常不錯,感興趣的朋友一起學(xué)習(xí)吧2016-08-08