JavaScript實現滑塊驗證案例
本文實例為大傢分享瞭JavaScript實現滑塊驗證的具體代碼,供大傢參考,具體內容如下
<!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') // 選中文字就會觸發這個事件 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) { //設置滑動塊的距離 this.style.left = left + 'px'; //設置背景的寬度 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; //設置滑動塊的距離 bg.style.width = 0; //設置背景的寬度 }; } </script> </html>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。