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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)