原生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>

 

效果图:

 

猜你喜欢

转载自www.cnblogs.com/shihaiying/p/11906350.html