仿支付宝滑块验证效果Jquery前端实现

仿支付宝滑块验证效果Jquery前端实现,在验证成功时,在进行其他的操作,例如发送手机验证码或者其他,本文以验证成功发送邮件为例。效果图如下

代码如下:

*{margin: 0px;padding: 0px;}
.sliding{width: 400px;height: 40px;margin: 50px auto;background:rgba(212, 212, 212, 1);text-align: center;line-height: 40px;position: relative;}
.sliding > p{width: 0px;height: 100%;position: absolute;top: 0;left: 0;background:#7BBB55;z-index: 99;color: #FFFFFF;text-align: center;overflow: hidden;}
.sliding > span{display: block;width: 46px;height: 100%;position: absolute;top: 0;left: 0;background-size: cover;cursor: pointer;z-index: 999;}
.span1_back{background: url(left.png) no-repeat center center;}
.span2_back{background: url(ok.png)no-repeat center center;}
<div class="sliding">
    请按住滑块,拖至最右侧。
    <p></p>
    <span class="span1_back"></span>
</div>
$(function(){
  $('.sliding > span').on('mousedown',function(ev){
    //获取鼠标摁下的位置
    var down_X=ev.clientX;
    //获取p,span的宽度
    var p_W=$('.sliding > p').get(0).offsetWidth;
    var span_X=$('.sliding > span').get(0).offsetLeft;
    $(document).get(0).onmousemove=function(ev){
      //获取鼠标移动的位置
      var move_X=ev.clientX;
      //用移动过后的位置减去鼠标摁下的位置加上p的宽度或者 span 的left 值 因为俩者是同步的 所以 减去 其中一个就好
      var size = move_X - down_X + p_W;              
      if(size>0){// 移动的时候判断size>0的时候执行,Math.min选取最小值,让拖动过程中不至于超出
        size=Math.min(($('.sliding').get(0).offsetWidth - $('.sliding > span').get(0).offsetWidth),size);
      }else{
        //小于0的时候 size =0; 防止有无聊的用户拖回 超出边界
        size=0;
      }
      $('.sliding > p').css('width', size + 'px');
      $('.sliding > span').css('left', size + 'px');
      //防止拖拽过程中选中文字
      return false;
    }
    $(document).get(0).onmouseup=function(){
      //鼠标松开执行,判段span到达边界时候执行
      if(($('.sliding > span').get(0).offsetLeft) >= ($('.sliding').get(0).offsetWidth - $('.sliding > span').get(0).offsetWidth)){
        //更改span的背景图片
        $('.sliding > span').attr('class','span2_back');
        //更改p标签中的内容
        $('.sliding > p').text('验证通过');
        //验证成功之后执行的方法
        successAfter();
        //删除鼠标摁下方法防止用户 无聊往回 推拽
        $('.sliding > span').off('mousedown');
      }else{
        //判断没到达边界让它再回到起点
        //利用jquery让p 和 span 回到起始状态
        $('.sliding > span').animate({left:'0px'},300);
        $('.sliding > p').animate({'0px'},300);
      }
      $(document).get(0).onmousemove=null; //最后让 鼠标移动 和 鼠标松开 事件停止 
      $(document).get(0).onmouseup=null;
    }
  })
});
原文地址:https://www.cnblogs.com/yeshaoxiang/p/7852768.html