您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)如何使用JavaScript實現(xiàn)滑塊驗證功能,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
具體內(nèi)容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } .box { position: relative; width: 500px; height: 40px; border: 1px solid #000; } p { position: relative; z-index: 5; font: 20px/40px '楷體'; text-align: center; color: rgba(95, 90, 90, 0.479); } .btn { width: 40px; height: 40px; border: 1px solid #ccc; box-sizing: border-box; background-color: #fff; cursor: pointer; z-index: 6; position: absolute; top: 0; left: 0; background-position: center; background-repeat: no-repeat; background-size: 50% auto; background-image: url(./圖1.png); } .bg { height: 100%; position: absolute; top: 0; left: 0; background-color: #7ac23c; } </style> </head> <body> <div class="box"> <div class="btn"></div> <p>拖動滑塊驗證</p> <div class="bg"></div> </div> </body> <script> //獲取事件 var box = document.querySelector('.box') var p = document.querySelector('p') var btn = document.querySelector('.btn') var bg = document.querySelector('.bg') // 選中文字就會觸發(fā)這個事件 this.box.onselectstart = function () { return false // 阻止默認行為 } //默認沒有驗證成功 var flag = false; //按下事件 btn.onmousedown = function () { var e1 = window.event; var x1 = e1.offsetX; //移動事件 btn.onmousemove = function () { var e2 = window.event; var x2 = e2.clientX //計算left的值 var left = x2 - x1 if (left > 0) { //設(shè)置滑動塊的距離 this.style.left = left + 'px'; //設(shè)置背景的寬度 bg.style.width = left + 'px'; if (left > box.offsetWidth - this.offsetWidth) { //驗證成功 flag = true; p.innerText = '通過驗證' p.style.color = '#000' //事件清除 this.onmousedown = null; this.onmousemove = null; } } } //鼠標松開 btn.onmouseup = function () { //事件清除 this.onmousemove = null; //判斷驗證是否成功 if (flag) { return } this.style.left = 0; //設(shè)置滑動塊的距離 bg.style.width = 0; //設(shè)置背景的寬度 }; } </script> </html>
關(guān)于“如何使用JavaScript實現(xiàn)滑塊驗證功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。